How to use different ifstream modes in c++?
Question
- According to the reference, if I use
ifstream infile ( "test.txt" , ifstream::in );
it willAllow input operations on the stream.
But what are some of the examples of the "input operations"? - Is
ifstream infile ( "test.txt" , ifstream::in | ifstream::binary );
the right syntax to use multiple flags? - Will it make a difference if I change
ifstream::
toiso::
?
Thank you
Solution
- According to the reference, if I use ifstream infile ( "test.txt" , ifstream::in ); it will Allow input operations on the stream. But what are some of the examples of the "input operations"?
Reading from a file which would mean everything an input stream can support. See istream
member functions. Typically, you can do both formatted (using >>
) and unformatted reads (using read
). Remember that ifstream
is a specialization of the basic_ifstream
template for char
type. Depending on your needs, say to read UTF-16 encoded file, you may have to use a different specialization (wifstream
) or even use a special locale (read this to know more about locales).
- Is ifstream infile ( "test.txt" , ifstream::in | ifstream::binary ); the right syntax to use multiple flags?
Yes.
- Will it make a difference if I change ifstream:: to iso:: ?
No.
OTHER TIPS
Stream operations are extraction <<
and insertion >>
. When you do the following assuming
file
is of fstream
type:
file << 5 << 6.5 << "Hello World!"; // insertion of data (output)
file >> x >> y >> str; // exaction of data (input)
You could also, deal with the stream
as a binary stream
. In that case, it doesn't really look like a "stream
" of data but that gives you random access to the data. In some cases you can't use the binary mode, especially if your data is not available like a network stream. Insertion and Extraction, are the two main operations on streams.
ifstream
is created as an input stream
by default. So, std::ios::in
is redundant in this case. You are using the flags correctly.
all streams inherit from ios
. So, the flags are available in both places, you can either retrieve them from ios
directly or from fstream
.