提问人:Jordan Baller 提问时间:4/9/2020 更新时间:4/9/2020 访问量:34
二进制文件中的信息未正确显示
Info from binary file doesn't show correctly
问:
我在二进制文件中有信息,其格式为(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);
}
答: 暂无答案
评论
int
sizeof(int)