对于数据记录应用程序,我必须将一些(以前)未知大小的 block 写入文件。为了方便阅读,我想添加有关 block 大小的信息。与 RAM 的大小相比,数据可能很大,因此在 RAM 中使用缓冲区的解决方案不是一个好主意。
我的计划是在block的开头预留一个int
,用tellp
存储它的位置,然后写block并统计它的大小,然后返回到长度信息的位置并写入实际尺寸:
// 1. some stuff was written to the file here
// 2. reserve space for block length information and store its position:
long len = 0;
off_t pos = outfile.tellp(); // get position where len will be stored
outfile.write(&len, sizeof(long)); // write a dummy len
// 3. a block of previously unknown length is written to the file here
// 4. return to the position of the block length and write the actual size:
outfile.seekp (pos);
outfile.write (&len,sizeof(long));
这是实现我想要的目标的合理方法还是存在重大缺陷/问题/陷阱?
最佳答案
您的序列化方法不完全符合要求,但是,是的,基本前提是合理的。
我采用了与此类似的方法,返回到正在生成的大型二进制日志文件的开头,以更新在文件开头找到的“索引” block ,这有助于以后遍历生成的数据。
不要忘记以下内容:
- 以二进制模式打开文件以避免序列化
10
成为其他东西; - 记录/限制值的格式(至少是字节顺序);
- 选择一个固定宽度的整数类型,例如
uint64_t
。
当然,如果有什么方法可以提前预测 block 大小,那么您就可以避免四处寻找。 :)
关于c++ - 登录文件后使用 tellp 和 seekp 设置 block 大小是否合理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32053864/