Is ios::in needed for ifstream's opened in binary mode?

catfish_deluxe_call_me_cd picture catfish_deluxe_call_me_cd · Sep 18, 2011 · Viewed 11.9k times · Source

What's the difference between these two? Isn't the in flag object thing redundant? Thanks.

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

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

Answer

Desmond Hume picture Desmond Hume · Sep 18, 2011

From the docs on ifstream class constructor:

binary (binary) Consider stream as binary rather than text.
in (input) Allow input operations on the stream.

So when reading from a file, I would use std::ifstream::in flag not because it's required (or not) but because it would be a good programming practice to let a programming interface know what you are going to use it for.

Edit:
The following is taken from http://www.cplusplus.com/doc/tutorial/files/, about open() member function though (but the constructors in the code in the question probably call open() copying the mode flags without modification).

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

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.

Nevertheless, many examples over the Web use ifstream::in when showing a construction of an ifstream object. Could really be some kind of a superstition practice, instead of a programming one.