1

I was able to read and write without setting any binary flag:

#include <fstream>
#include <iostream>

struct C {

    C(int X = 0, int Y = 0) :x(X), y(Y) {}

    int x; int y;
};

int main()
{
    C Point1(4, 9);
    C Point2;

    std::fstream IOFile("Test.txt", 
        std::ios_base::in | std::ios_base::out);

    IOFile.write((char const*)&Point1, sizeof(C));

    IOFile.seekg(std::ios_base::beg);

    IOFile.read((char*)&Point2, sizeof(C));

    IOFile.close();
}

The write and read functions returned the same data regardless of whether binary flag was set or not. So, where is this flag really necessary?

user963241
  • 6,758
  • 19
  • 65
  • 93
  • This code doesn't prove that what you read is what you wrote. It only proves that an error isn't generated. – lurker Nov 12 '15 at 04:08
  • Technically this is undefined behavior to [write to a text stream a character outside the printable characters range](http://stackoverflow.com/a/30891329/1708801). This will work on many systems but it could break in the future. – Shafik Yaghmour Nov 12 '15 at 04:10
  • In general you can't binary dump objects to files and back and expect it to work reliably. – Neil Kirk Nov 12 '15 at 04:18

2 Answers2

3

It is system dependent. UNIX/Linux does not make any difference between text mode and binary mode. Windows does though. So for maximum portability use binary whenever you read/write streams of raw data.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • I am using Windows OS. Would there be much difference? – user963241 Nov 12 '15 at 04:39
  • Yes it will, since the newlines are translated into `\r\n`. It happens to work in your case since you don't encounter those characters (13 and 10 in ASCII, respectively). But, to have a portable and correct code, you need to use binary mode. – vsoftco Nov 12 '15 at 04:42
2

On UNIX, there is no difference.

On Windows, LF (\n) is translated into the Windows CRLF (\r\n) line ending sequence when writing and vice versa when reading. That's if the file is opened in text mode. In binary mode no translation is done.

Pre-OSX Macs used CR (\r) as line endings, so \n was turned into \r when writing and the reverse when reading. OSX is a UNIX-based operating system so it performs no translation.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578