c++ - std::ofstream::write 添加字符

标签 c++ ofstream

我正在尝试使用 std::ofstream::write 方法编写二进制文件。我发现,有些字符不是按原样写的,例如:

std::ofstream in("testout");
int i =10;

in.write((const char *)(&i), sizeof(i));
in.close();

return 0;

将以下内容写入二进制文件:0d 0a 00 00 00 为什么会出现额外的 0d 字节?

最佳答案

您必须在打开时指定 std::ofstream::binary

否则,在文本文件模式的 Windows 上,程序中的 \n (0x0a) 将转换为/自 \r\n (0x0d 0x0a) 写入/读取文件时。

关于c++ - std::ofstream::write 添加字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21982768/

相关文章:

c++ - 数据结构对齐

c# - C# 和 C++ 之间的指针 - p/invoke

C++ 索引语法 : two libraries use different indexing syntax: 0 based and 1 based index

c++ 可以使用 fstream infile 从最近使用的 ofstream outfile 中收集数据吗?

c++ - 为什么ofstream不能用bind绑定(bind)?

c++ - 在不带 BOM 编码的 UCS-2 LE 中使用标准 ofstream 编写 C++ 文件

c++ - 如何让 Swig 生成 Python 类而不是自由函数?

c++ - 吞吐量网络估计

c++ - 在 C++ 中逐行读取二进制文件

c++ - 如何封装两个流缓冲区