简体   繁体   English

将字节写入.Bin文件

[英]writing Bytes into a .Bin file

I have a vector in C++ that I want to write it to a .bin file. 我有一个C ++中的向量,我想将它写入.bin文件。 this vector's type is byte , and the number of bytes could be huge, maybe millions. 这个向量的类型是bytebyte数可能很大,可能是数百万。 I am doing it like this: 我是这样做的:

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 is my vector which contains bytes and lets say its size is 100,000. depthQueue是我的向量,包含字节,让我们说它的大小是100,000。
Sometimes I don't get this error, but the bin file is empty. 有时我没有收到此错误,但bin文件为空。
Sometime I get heap error. 有时我得到堆错误。
Somtimes when I debug this, it seems that malloc doesn't allocate the space. 有时当我调试它时,似乎malloc没有分配空间。 Is the problem is with space? 问题是空间吗?

Or is chunk of sequential memory is so long and it can't write in bin? 或者顺序存储器的块是如此之长,它不能写入bin?

You don't need hardly any of that. 你几乎不需要任何这些。 vector contents are guaranteed to be contiguous in memory, so you can just write from it directly: vector内容保证在内存中是连续的,所以你可以直接从它写入:

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

Note a possible bug in your code: if the vector is indeed vector<Byte> , then you should not be multiplying its size by 320*240. 请注意代码中可能存在的错误:如果向量确实是vector<Byte> ,则不应将其大小乘以320 * 240。

EDIT: More fixes to the fwrite() call: The 2nd parameter already contains the sizeof (Byte) factor, so don't do that multiplication again in the 3rd parameter either (even though sizeof (Byte) is probably 1 so it doesn't matter). 编辑:更多修复fwrite()调用:第二个参数已经包含sizeof (Byte)因子,所以不要在第三个参数中再次进行乘法(即使sizeof (Byte)可能是1,所以它不会无所谓)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM