James Kanze 对 How to copy a .txt file to a char array in c++ 的评论听起来好像为了确保标准字符串在由标准字符串构造函数迭代时能够获得文件的准确二进制内容,必须同时执行以下两项操作:
- 以二进制模式打开文件,
- 确保文件包含“C”语言环境。
在代码中,我猜这意味着:
std::ifstream in(filename, ios_base::binary);
in.imbue(std::locale("C"));
真的有必要吗?更具体地说,为什么区域设置会在以二进制模式打开文件时产生任何影响?
请注意,我想做的或多或少是上述问题的内容:
std::string contents(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
最佳答案
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.
我认为
std::ifstream in(filename, ios_base::binary);
与:
in.imbue(std::locale("C"));
没有意义。
要么流处于二进制模式,并且区域设置不适用,要么程序员选择设置区域设置,但随后他/她隐式意味着流以文本模式打开(ios_base::binary
不应传递给流构造函数)。在这种情况下,读取的数据可能等于也可能不等于文件中的数据,具体取决于操作系统和文件的内容。
关于c++ - 二进制模式下的 std::ifstream 和 C++ 中的区域设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43950649/