在C错误中读/写int二进制文件

时间:2017-04-06 10:06:06

标签: c binaryfiles

我在C中读取/写入二进制文件时遇到错误。问题是: - 我使用fwrite将int(例如2)写入文件 - 我尝试使用fread从文件中读取此int - 当我读它时,它不是2,而是一些长数,例如967899906或2071332354或1030372866(总是不同)。

我在C中写入二进制文件,如下所示:

 letter = letter || Char.IsLetter(character);

然后我从文件中读到这样的内容:

FILE * writeFile = fopen("test.bin","wb");

//test int vars
int test1 = 1;
int test2 = 2;
int test3 = 3;

//writing some ints to binary file
fwrite(&test1,1,1, writeFile);
fwrite(&test2,1,1, writeFile);
fwrite(&test3,1,1, writeFile);

fclose(writeFile);

2 个答案:

答案 0 :(得分:0)

fwrite希望第二个参数是要写入的数据大小,因此在您的情况下sizeof(int)

fread

也是如此
#include <stdio.h>

int main(void)
{
     FILE * writeFile = fopen("test.bin","wb");

     if (writeFile != NULL)
     {
         //test int vars
         int test1 = 1;
         int test2 = 2;
         int test3 = 3;

         //writing some ints to binary file
         fwrite(&test1,sizeof(test1),1, writeFile);
         fwrite(&test2,sizeof(test2),1, writeFile);
         fwrite(&test3,sizeof(test3),1, writeFile);

         fclose(writeFile);
     }
     else
     {
         perror("Error opening file to write: ");
         return 1;
     }


     FILE *readFile = fopen("test.bin","rb");
     if (readFile != NULL)
     {
         int data;
         while(fread(&data,sizeof(data),1, readFile)==1){
            printf("%d\n", data);
         }
         fclose(readFile);
     }
     else
     {
         perror("Error opening file to read: ");
         return 1;
     }

    return 0;
}

提示:始终测试fopen是否成功。

修改

要使用1字节变量(如注释),只需使用uint8_t变量

#include <stdio.h>
#include <stdint.h>

int main(void)
{
     FILE * writeFile = fopen("test.bin","wb");

     if (writeFile != NULL)
     {
         //test int vars
         uint8_t test1 = 1;
         uint8_t test2 = 2;
         uint8_t test3 = 3;

         //writing some ints to binary file
         fwrite(&test1,sizeof(test1),1, writeFile);
         fwrite(&test2,sizeof(test2),1, writeFile);
         fwrite(&test3,sizeof(test3),1, writeFile);

         fclose(writeFile);
     }
     else
     {
         perror("Error opening file to write: ");
         return 1;
     }


     FILE *readFile = fopen("test.bin","rb");
     if (readFile != NULL)
     {
         uint8_t data;
         while(fread(&data,sizeof(data),1, readFile)==1){
            printf("%d\n", data);
         }
         fclose(readFile);
     }
     else
     {
         perror("Error opening file to read: ");
         return 1;
     }

    return 0;
}

答案 1 :(得分:0)

LP是正确的,如果你有0 <= x <= 255的范围,你应该考虑uint8_t

但是,如果你想使用int,你可能会得到垃圾的原因是因为

fread(&data,1,1, readFile)==1)

读取单个字节的数据并将其放在指针指定的位置。在您的情况下,这将是data的最低字节。 Ints通常为4个字节长,因此其他3个字节将保持不变。其他三个字节是什么?好吧,在你的情况下,它们可能是任何东西,因为data在堆栈上未初始化。