繁体   English   中英

将数组保存到二进制文件不起作用C ++

[英]Save array to binary file not working c++

我在C ++中有一个无符号的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()不承诺给您归零的内存。 为此,请使用calloc()进行分配,并将内存或memset()归零,以将已分配的内存归零。 (尽管所有这些都是C东西;对于C ++,最好使用std::vector类的东西而不是原始C数组。)

C ++代码以不同的方式编写:

std::vector<unsigned char> vectorToWrite = { 0, 1, 2 };
vectorToWrite.resize( 720 );
std::ofstream file( "filePath.bin", std::ios::out | std::ios::binary );
if( !file ) {
    // error handling
}
file.write( vectorToWrite.data(), vectorToWrite.size() * sizeof( decltype(vectorToWrite)::value_type ) );

注意:我将sizeof( decltype(vectorToWrite)::value_type )放在此处,因此,如果您以后更改矢量数据,它将仍然可以正常工作而无需进一步更改,但是在使用char情况下,由于sizeof(char)始终等于,可以将其完全省略1个

暂无
暂无

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

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