二进制文件中的信息未正确显示

Info from binary file doesn't show correctly

提问人:Jordan Baller 提问时间:4/9/2020 更新时间:4/9/2020 访问量:34

问:

我在二进制文件中有信息,其格式为(1 int, 10char),如下所示:“21fghjklbnv2qwertyuiop”等。为什么我不能在文本文件中正确写入信息(名称:10char 年龄:int)?它只写一个整数,而且是错误的。我尝试改变内存的分配方式,但它使情况变得更糟

void Task2_and_3(int i, int n)
{
    int *Number_Filep = (int*)malloc(sizeof(int));
    char *Wordp = (char*)malloc(sizeof(char)*11);
    i = 0;
    FILE*f;
    if ((f = fopen("Test2.bin", "rb"))==NULL)
    {
        printf("File cannot be opened");
        exit(1);
    }
    if(Number_Filep == NULL)
    {
         free(Number_Filep);
         free(Wordp);
         exit(2);
    }
    else if(Wordp == NULL)
    {
        free(Number_Filep);
        free(Wordp);
        exit(5);
    }
    while(1)
    {
       if(feof(f))
       {
           break;
       }
       if(i>=1)
       {
           int* temp = Number_Filep;
           char* tempw = Wordp;
           Number_Filep = realloc(Number_Filep, sizeof(int));
           Wordp = realloc(Wordp, 11*sizeof(char));
           if(Number_Filep  == NULL)
           {
              free(temp);
              free(tempw);
              printf("Error");
              exit(3);
           }
           else if(Wordp == NULL)
           {
              free(temp);
              free(tempw);
              printf("Error");
              exit(3);
           }
       }
        fread(Number_Filep, sizeof(int), 1,f);
        fread(Wordp, sizeof(char), 11 ,f);
        i++;
    }
    fclose(f);
    FILE*fp;
    if ((fp = fopen("Data.txt", "w"))==NULL)
    {
        printf("File cannot be opened");
        exit(4);
    }
    n=0;
   /* for(n=0;n<i;n++)
    {*/
    fprintf(fp,"Name: %s", Wordp);
    fprintf(fp,"\n");
    fprintf(fp,"Age: %d", *Number_Filep);
    fprintf(fp,"\n");
    //}
    fclose(fp);
    free(Number_Filep);
    free(Wordp);

}
C 文件-IO EOF

评论

0赞 wildplasser 4/9/2020
stackoverflow.com/q/5431941/905902取而代之的是:检查 fread() 的返回值
0赞 Ruks 4/9/2020
请注意,在二进制文件中,应始终占用 4 个字节(或实现定义,但通常是 4 个字节)。intsizeof(int)
0赞 Jordan Baller 4/10/2020
@wildplasser我检查了 fread() 的返回值,这肯定是有问题的。它可以访问未分配的内存吗?
0赞 wildplasser 4/10/2020
不,您只是想超越 EOF。

答: 暂无答案