如何在事先不知道长度的情况下写出一系列数字(二进制),前面加上它的长度?
我可以将数字系列写入临时缓冲区(例如 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/