Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

ifstream

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);

like image 378
catfish_deluxe_call_me_cd Avatar asked Sep 18 '11 18:09

catfish_deluxe_call_me_cd


People also ask

What is ios :: binary used for?

ios::binary This causes the file to be accessed as a binary file. Most likely you will need to set this option. If you forget to set this option, many strange problems will occur when reading certain characters like `end of line' and `end of file'.

What is binary mode C++?

A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equals to the data that were earlier written out to that stream. Implementations are only allowed to append a number of null characters to the end of the stream.


1 Answers

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.

like image 181
Desmond Hume Avatar answered Oct 06 '22 00:10

Desmond Hume