Is ios :: in needed for ifstream open in binary mode?

What is the difference between the two? Is the thing in flag object ruled out? Thanks.

std::ifstream file1("one.bin", std::ifstream::in | std::ifstream::binary);

std::ifstream file2("two.bin", std::ifstream::binary);

+7
source share
3 answers

From the docs in the ifstream constructor of the class:

binary (binary). Consider the stream as binary, not text. c (input) Allow input operations on the stream.

Therefore, when reading from a file, I would use the std::ifstream::in flag not because it was required (or not), but because it would be good programming practice so that the programming interface knows what you are going to use it for.

Edit:
The following is taken from http://www.cplusplus.com/doc/tutorial/files/ : open() is a member function (but the constructors in the code in the question probably cause open() copy the mode flags unchanged).

class: default mode parameter
ofstream: ios :: out
ifstream: ios :: in
fstream: ios :: in | ios :: out

For the ifstream andstream classes, ios :: in and ios :: out are automatically and, accordingly, it is assumed even if the mode does not include them as a second argument in the open () element of the function.

However, many examples on the Internet use ifstream::in when showing the construction of an ifstream object. Perhaps it was some kind of superstition practice, not programming.

+5
source

I can not find official documentation on the Internet.

Edit I can't even find the correct link in my copy of the Josuttis Book , eighth print. It should have been in section 13.9 s. 627-631

Empirical evidence suggests that this is redundant IFF, none of std :: ios :: in or std :: ios: out passed:

 #include <fstream> #include <iostream> int main(int argc, char** args) { std::ifstream ifs(args[0], std::ios::binary); std::cout << ifs.rdbuf() << std::flush; return 0; } 

succeeds:

 test | md5sum md5sum test 

shows the same amount of hashes.


  // ... std::ifstream ifs(args[0], std::ios::out | std::ios::binary); 

will fail (output with zero byte)

 test | wc -c # shows 0 
+1
source

binary , in this case applies only to the read or write method. In normal mode, on windows, '\n' translates to '\r''\n' . This can affect both reading and writing, so binary mode disables this. out|binary has the same meaning as in|binary

+1
source

All Articles