我有一个 C++ vector ,我想将它写入 .bin 文件。
这个 vector 的类型是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
是我的 vector ,它包含字节,假设它的大小是 100,000。
有时我没有得到这个错误,但是 bin 文件是空的。
有时我会收到堆错误。
有时当我调试它时,似乎 malloc 没有分配空间。
问题出在空间上吗?
或者是连续内存块太长,无法写入 bin?
最佳答案
您几乎不需要这些。 vector
内容保证在内存中是连续的,所以你可以直接从它写:
fwrite(&depthQueue[0], sizeof (Byte), depthQueue.size(), pFiledep);
请注意您的代码中可能存在的错误:如果 vector 确实是 vector<Byte>
,那么您不应该将其大小乘以 320*240。
编辑 fwrite()
的更多修复调用:第二个参数已包含 sizeof (Byte)
因数,因此也不要在第三个参数中再次执行该乘法运算(即使 sizeof (Byte)
可能为 1,所以这无关紧要)。
关于c++ - 将字节写入 .Bin 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437864/