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?
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.