catfish_deluxe_call_me_cd catfish_deluxe_call_me_cd - 2 years ago 202
C++ Question

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

What's the difference between these two? Isn't the

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 Source

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.

The following is taken from, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download