将字节写入.Bin文件

时间:2012-11-18 05:53:59

标签: c++ binaryfiles fstream ofstream writetofile

我有一个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中写入?

1 个答案:

答案 0 :(得分:2)

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

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

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

编辑:对fwrite()调用的更多修正:第二个参数已包含sizeof (Byte)因子,因此请勿在第3个参数中再次进行相乘(即使sizeof (Byte)可能是1,所以无关紧要。)

相关问题