Reputation: 25551
std::fstream
has the option to consider streams as binary, rather than textual. What's the difference?
As far as I know, it all depends on how the file is opened in other programs. If I write A
to a binary stream, it'll just get converted to 01000001
(65, A
's ASCII code) - the exact same representation. That can be read as the letter "A" in text editors, or the binary sequence 01000001
for other programs.
Am I missing something, or does it not make any difference whether a stream is considered binary or not?
Upvotes: 3
Views: 1237
Reputation: 7939
On Linux/Unix/Android there is no difference.
On a Mac OS/X or later there is no difference, but I think older Macs might change an '\n' to an '\r' on reading, and the reverse on writing (only for a Text stream).
On Windows, for a text stream some characters get treated specially. A '\n' character is written as "\r\n", and a "\r\n" pair is read as '\n'. An '\0x1A' character is treated as "end of file" and terminates reading.
I think Symbian PalmOS/WebOS behave the same as Windows.
A binary stream just writes bytes and won't do any transformation on any platform.
Upvotes: 1
Reputation: 12184
If you open it as text then the C or C++ runtime will perform newline conversions depending on the host (Windows or linux).
Upvotes: 1
Reputation: 168596
The practical difference is the treatment of line-ending sequences on Microsoft operating systems.
Binary streams return the data in the file precisely as it is stored. Text streams normalize line-ending sequences, replacing them with '\n'
.
Upvotes: 1
Reputation: 67362
You got it the other way around, it's text streams that are special, specifically because of the \n
translation to either \n
or \r\n
(or even \r
..) depending on your system.
Upvotes: 1
Reputation: 363487
In text streams, newline characters may be translated to and from the \n
character; with binary streams, this doesn't happen. The reason is that different OS's have different conventions for storing newlines; Unix uses \n
, Windows \r\n
, and old-school Macs used \r
. To a C++ program using text streams, these all appear as \n
.
Upvotes: 5