c++ - 我可以对文件进行无格式写入,然后对整数类型的文件进行格式化读取吗?

标签 c++ binaryfiles ifstream ofstream formatted

鉴于我将整数的 vector 写入未格式化的临时文件:

ofstream foo("foo.txt", ios::binary);
const auto length= size(output);

foo.write(reinterpret_cast<const char*>(length), sizeof(length));

if(!empty(input)) foo.write(reinterpret_cast<const char*>(data(output)), sizeof(decltype(output)::value_type) * length);

我可以稍后从 inputoutput 类型相同的文件中执行以下格式化读取吗:

ifstream foo("foo.txt", ios::binary);
size_t size;

foo.read(reinterpret_cast<char*>(size), sizeof(size));
input.resize(size);

if(!empty(input)) copy(istream_iterator<decltype(output)::value_type>(foo), istream_iterator<decltype(output)::value_type>(), begin(input));

最佳答案

Can I do an Unformatted Write to a File Then a Formatted Read From a File for Integral Types?

不,你不能那样做。

使用无格式写入写入数据的文件内容与格式化写入有很大不同。格式化的读取无法准确解释未格式化的数据。

关于c++ - 我可以对文件进行无格式写入,然后对整数类型的文件进行格式化读取吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37889732/

相关文章:

C++循环继承依赖

c - 可移植 C 二进制序列化原语

c - GCC不同的实际内存分配量,然后我分配给程序中的变量

c++ - 读取和打印文件中的值

c++ - 关于读取 UTF-8 编码文本时 Ifstream get() 方法行为的解释 (C++)

c++ - 使用 std::filebuf 时检测底层文件的完整性丢失?

c++ - 为什么使用具有特殊含义的覆盖和最终标识符而不是保留关键字?

c++ - 如何在 ARM 的 IAR 嵌入式工作台中编译包含 C 和 C++ 源文件的项目?

c++ - 使用 memcpy() 函数将字节从 unsigned char 数组放入 std::string

MATLAB:读取无符号 16 位二进制文​​件的两个字节