Is it recommended to always open file using 'binary' mode?

623 views Asked by At

I have a generic function:

bool WriteFile(const string& strFileContent, const wpath& pathFile)

In this function I have the following line:

std::ofstream outStream(pathFile.string().c_str(), std::ios::out);

Since this function is generic, I sometimes use it to write binary files. I noticed that using openmode std::ios::out is not the right one for binary data and the written files are not as I expected, meaning, files are not equal to the actual data defined in strFileContent.

So I've made this simple fix:

std::ofstream outStream(pathFile.string().c_str(), std::ios::out | std::ios::binary);

Which resolved the issue for binary files and also worked perfect for text files as well.

Question

if open mode std::ios::out | std::ios::binary works for both binary and text data, isn't one of them redundant?
If so, should I always use std::ios::out | std::ios::binary?
If not, In which cases this using std::ios::out | std::ios::binary is not recommended?

2

There are 2 answers

0
William J Bagshaw On

Opening as text will modify what it thinks is, end of line characters as you read or write the file. For pure text files I would open as text. There are two advantages.

  • The code is more portable to other platforms.

  • The code is more compatible with files that originated from other platforms.

    So, for example, you may see a benefit of using text format for CVS, XML or HTML files that tend not to contain raw binary data.

Unfortunately it is not a guarantee that the above will work, but in most cases it helps.

0
Rick On

I've read some related posts and can't find much new stuff.
Except the newline conversion, I can't find any other reasons to prefer text mode.
By the way, in the GNU C Library, and on all POSIX systems, there is no difference between text streams and binary streams.

see here for how this is explained in GCC documentation.

I would really want to find some examples about the emphasised text.

Since a binary stream is always more capable and more predictable than a text stream, you might wonder what purpose text streams serve. Why not simply always use binary streams? The answer is that on these operating systems, text and binary streams use different file formats, and the only way to read or write “an ordinary file of text” that can work with other text-oriented programs is through a text stream.