c++ - 登录文件后使用 tellp 和 seekp 设置 block 大小是否合理?

标签 c++ file

对于数据记录应用程序,我必须将一些(以前)未知大小的 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/

相关文章:

php - Facebook HipHop (PHP to C++) 能否在Windows上编译运行

c - C中文件操作期间的运行时错误

java - 如何查找 Zip 文件目录中的任何文件

C语言: Error in implementing binary search tree using structures

c++ - 是否可以在 C++ 中新创建的线程中加入子线程?

C++ Treiber Stack 和原子 next 指针

c++ - 在 Ubuntu 中使用 videoWriter(OpenCV) 将视频保存为 MP4 时出错

c++ - 无法从 'const char [3]' 转换为 'char *' x100000 (Qt Creator C++ Windows 32)

java - 列出android中一种类型的所有文件

iOS:无法将文件保存到 'Application Support' 文件夹,但可以保存到 'Documents'