c++ - 使用 ofstream 写入带有临时缓冲区的文件

标签 c++ iostream

如何在事先不知道长度的情况下写出一系列数字(二进制​​),前面加上它的长度?

我可以将数字系列写入临时缓冲区(例如 buf.write() ),确定缓冲区长度,然后将缓冲区复制到 ofstream 中吗?之后(例如 ofs << buf)?

最佳答案

由于您正在以二进制模式写入文件,因此请为数量保留一个位置。

例如,让我们为数量设置一个 32 位值。我们可以把它写在文件的开头:

uint32_t number_size = 0U;

// Open output file for read & write.
// Reserve space for the quantity by writing dummy value.
output_file.write((char *)&number_size, sizeof(number_size));

// Perform calculations & writing to file, incrementing "number_size"  

// Write the number size to the top of the file:
output_file.seekp(0, SEEK_BEG);
output_file.write((char *)&number_size, sizeof(number_size));

你可以把数量变量放在任何地方,只要记住它的文件位置。完成后,寻找该位置并将其写入。

关于c++ - 使用 ofstream 写入带有临时缓冲区的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593535/

相关文章:

c++ - 条件输出

c++ - 如何在 Visual Studio 中使用 C++ 解压缩压缩文件 (.zip)

c++ - 在析构函数调用未定义行为后访问内存吗?

c++ - boost::asio::streambuf 与 wchar_t

c++ - Cin 没有操作数 >>

c++ - 我什么时候应该关注 std::iostream::sentry?

c++ - 在析构函数之前省略关键字 virtual 仍然有效

c++ - SIMD程序编译问题

c++ - 复制构造函数在哪里被调用?

c++ - 新编译器 - 使用 Cout?