gpt4 book ai didi

c++ - 将数组保存到二进制文件不工作 C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:59:23 33 4
gpt4 key购买 nike

我在 C++ 中有一个 unsigned char 数组,我想将它的位保存到一个文件中。

例如,如果我有下面的数组

arr[0] = 0;
arr[1] = 1;
arr[2] = 2;

我想将其保存到文件中,使文件的二进制数据看起来像这样(没有空格)。

00000000 00000001 00000010

我试过下面这段代码,但它似乎不起作用。我给程序一个大小为 0 字节的空白文件,程序运行后文件大小保持为 0 字节(没有任何内容写入其中)。

// Create unsigned char array
unsigned char *arrayToWrite= (unsigned char*)malloc(sizeof(unsigned char)*720);

// Populate it with some test values
arrayToWrite[0] = 0;
arrayToWrite[1] = 1;
arrayToWrite[2] = 2;

// Open the file I want to write to
FILE *dat;
dat = fopen("filePath.bin", "wb");

// Write array to file
fwrite(&arrayToWrite, sizeof(char)*720, 1, dat);
fclose(dat);

我希望在该程序运行后,文件“filePath.bin”的长度为 720 字节,除了我填充测试数据的第一和第二位置外,大部分填充了 0。

我做错了什么?任何帮助将非常感激!谢谢!

最佳答案

这里的基本问题是您将指针传递给 arrayToWrite 变量,而不是传递给数组本身。将 fwrite(&arrayToWrite... 更改为 fwrite(arrayToWrite...

顺便说一句,malloc() 不 promise 给你零内存。为此,使用 calloc() 分配内存并将其归零,或使用 memset() 将已分配的内存归零。 (尽管所有这些更像是 C 语言;对于 C++,您最好使用类似 std::vector 的东西而不是原始 C 数组。)

关于c++ - 将数组保存到二进制文件不工作 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48193667/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com