简体   繁体   中英

std::ifstream in binary mode and locale in C++

A comment by James Kanze on How to copy a .txt file to a char array in c++ makes it sound like in order to be sure that a standard string would get the exact binary contents of a file when iterated through by a standard string constructor, one would have to both:

  • open the file in binary mode,
  • ensure that the file is imbued with the "C" locale.

In code, I'm guessing that means:

std::ifstream in(filename, ios_base::binary);
in.imbue(std::locale("C"));

Is that really necessary? More specifically, why would the locale have any impact when the file is opened in binary mode?

Note that what I am trying to do is more or less what the above mentioned question was about:

std::string contents(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());

Based on binary and text modes :

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.

I think

std::ifstream in(filename, ios_base::binary);

together with:

in.imbue(std::locale("C"));

does not make sense.

Either the stream is in binary mode, and the locale does not apply, or the programmer chooses to set the locale, but then he/she implicitly means that the stream is open in text mode ( ios_base::binary should not be passed to the stream constructor). In that case, the read data may or may not equal to the data in the file, depending on the OS and the contents of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM