登录到文件后使用tellp和seekp来设置块大小是否合理?

时间:2015-08-17 15:11:11

标签: c++ file

对于数据记录应用程序,我将不得不将一些(先前)未知大小的块写入文件中。为了方便阅读,我想添加有关块大小的信息。与RAM的大小相比,数据可能很大,因此在RAM中使用缓冲区的解决方案并不是一个好主意。

我的计划是在块的开头保留int,用tellp存储其位置,然后写入块并计算其大小,然后返回到长度信息的位置,写下实际尺寸:

  // 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));

这是实现我想要的合理方式还是有明显的缺点/问题/陷阱?

1 个答案:

答案 0 :(得分:1)

您的序列化方法不是很划清,但是,是的,基本前提是声音

我采用与此类似的方法,在生成时返回到大型二进制日志文件的开头,以更新在文件开头找到的“索引”块,以帮助稍后遍历生成的数据。

不要忘记以下内容:

  • 以二进制模式打开文件以避免例如序列化10成为别的东西;
  • 记录/约束值的格式(至少是字节序);
  • 选择固定宽度的整数类型,例如uint64_t

当然,如果您有任何方法可以提前预测块大小,那么您可以避免所有的搜索。 :)

相关问题