Is ios::in needed for ifstream's opened in binary mode?
What's the difference between these two? Isn't th开发者_如何学Pythone 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);
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::outFor 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.
binary
, in this case, only refers to the method of reading or writing. In regular mode on windows, '\n'
is translated to '\r''\n'
. This can affect both reading and writing, so binary mode turns this off. out|binary
makes just as much sense as in|binary
I can't find authoritative documentation online.
Edit I can't even find a proper reference in my copy the Josuttis Book, 8th printing. It should have been in section 13.9 pp. 627-631
Empirical evidence suggests it is redundant IFF none of std::ios::in or std::ios:out are 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
show the same hash sum.
// ...
std::ifstream ifs(args[0], std::ios::out | std::ios::binary);
will fail (zero bytes output)
test | wc -c # shows 0
From cplusplus.com reference page, there is no difference.
in
is always set forifstream
objects (even if explicitly not set in argument mode).
It's the same for ofstream
. Therefore, you don't need to set std::ios::in
for ifstream
or std::ios::out
for ofstream
, even if you have set std::ios::binary
which omits the in/out
mode.
精彩评论