将字节写入 .箱文件
writing Bytes into a .Bin file
我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,所以没关系)。
相关文章:
- 在UNIX系统中使用DIR查找文件的字节大小
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 如何在文件中查找字节序列
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 如何使用 fprintf 将连续的 512 字节保存到文件中
- 用于 progmem 的C++和头文件压缩的 Web 文件字节数组
- 为什么未关闭的文件大小为 4 字节
- 我能确定从文件中读取的 32 字节二进制数据等于 256 位吗?
- Ascii .txt文件到字节数组 - C++
- 多部分/表单数据丢失大文件的字节
- 我该如何循环遍历我的数组(缓冲区——包含一个文本文件),并将其打印成30字节的块
- 程序错误地读取了二进制文件的一个字节
- 如何从 C 或 C++ 格式的文件中删除字节?
- C++ - 将任何文件的字节读取到无符号字符数组中
- ofstream将额外的零字节写入Unix服务器上的文件
- 传输文件一次又一次地发送相同的字节
- 编码大于原始文本:如何获取零和一的字符串并将它们作为实际字节写入文件
- 查找二进制文件中字节序列的所有匹配项
- 如何从 GDI+ 图元文件对象获取原始图元文件字节