将字节写入 .箱文件

writing Bytes into a .Bin file

本文关键字:文件 字节      更新时间:2023-10-16

我C++中有一个向量,我想将其写入.bin文件。这个向量的类型是 byte ,字节数可能很大,也许是数百万。我是这样做的:

if (depthQueue.empty())
    return;
FILE* pFiledep;
pFiledep = fopen("depth.bin", "wb");
if (pFiledep == NULL)
    return;
byte* depthbuff = (byte*) malloc(depthQueue.size() * 320 * 240 * sizeof(byte));
if(depthbuff)
{
  for(int m = 0; m < depthQueue.size(); m++)
  {
    byte b = depthQueue[m];
    depthbuff[m] = b;
  }
  fwrite(depthbuff, sizeof(byte),
        depthQueue.size() * 320 * 240 * sizeof(byte), pFiledep);
  fclose(pFiledep);
  free(depthbuff);
}

depthQueue是我的向量,它包含字节,假设它的大小是 100,000。
有时我没有收到此错误,但 bin 文件为空。
有时我收到堆错误。
当我调试它时,似乎 malloc 没有分配空间。问题出在空间上吗?

还是顺序内存块太长,无法写入 bin?

你几乎不需要这些。 vector内容保证在内存中是连续的,因此您可以直接从内存中写入:

fwrite(&depthQueue[0], sizeof (Byte), depthQueue.size(), pFiledep);

注意代码中可能存在的一个错误:如果向量确实是vector<Byte>,那么你不应该将其大小乘以 320*240。

编辑:fwrite()调用的更多修复:第二个参数已经包含sizeof (Byte)因子,所以也不要在第三个参数中再次进行乘法(即使sizeof (Byte)可能是 1,所以没关系)。