用临时缓冲区使用ofstream写入临时缓冲区
问题描述:
如何在不知道事先知道的长度的情况下编写一系列数字(二进制)用临时缓冲区使用ofstream写入临时缓冲区
我可以将数字序列写入临时缓冲区(例如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));
您可以任何地方数量变量,只记得它的文件位置。完成后,寻找该位置并将其写入。
+0
我会坚持这一点,谢谢 – Midas 2014-09-02 21:04:30
你究竟在做什么? – 0x499602D2 2014-08-31 15:45:24
1.不可以。如果你不知道它的长度,你怎么写?是的。 – 2014-08-31 15:49:29
1.将数据写入缓冲区 - 2.确定缓冲区长度 - 3.将文件写入长度 - 4.将数据写入文件 – Midas 2014-08-31 16:00:29