5

In my experiments with the following code snippet, I did not find any particular difference whether i created the streams with/without the ios:binary mode:

int main()
{
    ifstream ostr("Main.cpp", ios::in | ios::binary | ios::ate);
    if (ostr.is_open())
    {
        int size = ostr.tellg();
        char * memBlock = new char[size + 1];
        ostr.seekg(0, ios::beg);
        ostr.read(memBlock, size);
        memBlock[size] = '\0';
        ofstream file("trip.cpp", ios::out | ios::binary);
        file.write(memBlock, size);
        ostr.close();
    }
}

Here I am trying to copy the original source file into another file with a different name.

My question is what is the difference between the read/write calls(which are associated with binary file IO) when an fstream object is opened with/without ios::binary mode ? Is there any advantage of using the binary mode ? when to and when not to use it when doing file IO ?

Arun
  • 3,138
  • 4
  • 30
  • 41

2 Answers2

11

The only difference between binary and text mode is how the '\n' character is treated.

In binary mode there is no translation.

In text mode \n is translated on write into a the end of line sequence.
In text mode end of line sequence is translated on read into \n.

The end of line sequence is platform dependant.

Examples:

ASCII based systems:

LF    ('\0x0A'):      Multics, Mac OS X, BeOS, Amiga, RISC OS
CRLF  ('\0x0D\0x0A'): Microsoft Windows, DEC TOPS-10, RT-11
CR:   ('\0x0D'):      TRS-80, Mac OS Pre X
RS:   ('\0x1E'):      QNX pre-POSIX implementation.
Community
  • 1
  • 1
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • I understood what you have said. But can you elaborate a bit on where we should choose one over another(with/without ios::binary) ? – Arun Oct 08 '12 at 00:17
  • 1
    Personally I never have a need for the translation so I would always use binary mode. But if you are generating a text file and want to interact with the local OS text editing software then text mode may be appropriate (though note modern text editing software will cope with just the '\n' from binary mode (or line termination sequence from other systems but you need to check)). – Martin York Oct 08 '12 at 03:45
2

When you want to write files in binary, with no modifications taking place to your data, specify the ios::binary flag. When you want to write files in text mode, don't specify ios::binary, and you may get things like line ending translation. If you're on a UNIX-like platform, binary and text formats are the same, so you won't see any difference.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278