使用流写入具有临时缓冲区的文件

Write to file with temporary buffer using ofstream

本文关键字:缓冲区 文件      更新时间:2023-10-16

在事先不知道长度的情况下,如何编写一系列以其长度开头的数字(二进制)?

我可以将数字序列写入临时缓冲区(例如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));

您可以将数量变量放置在任何位置,只需记住其文件位置即可。完成后,查找该位置并将其写入。