c++ - 二进制模式下的 std::ifstream 和 C++ 中的区域设置

标签 c++ string file iterator locale

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

最佳答案

基于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.

我认为

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/

相关文章:

iphone - FMDB数据库WithPath : not writing to disk

c++ - 创建一个固定大小的 std::vector 并写入元素

c++ - std::set_difference 是否可以比较集合和映射键?

c# - 在 C# 中,如何计算字符串数组的每个索引中的单词数?

java - 如何使用正则表达式从字符串中删除破折号(-),除了java中的数字和单词之间?

java - Maven项目中的静态文件放在哪里

c++ - 删除整数指针时析构函数末尾的段错误

c++ - "int a, b;"和 "int a; int b;"之间的性能差异?

c++ - 为什么 fstream.open(filename) 使用文字而不是生成的字符串?

c# - 删除并重新创建后,幽灵文件仍然存在