当我尝试从文件中读取整数时,代码最终读取的数字与预期不同。
数据文件包含以下数字:
1111 111 222 333 444 555 666 777 888 -1
当我读取文件时,它返回以下数字:
825307441 825307424 842150432 858993440 875836448
892679456 909522464 926365472 943208480 170994976
为什么会这样?
相关代码:
/* A file named data contains some integer numbers.write a program to
read these numbers and store the odd numbers in one file and store
the even numbers in file.*/
int main()
{
FILE *fp1,*fp2,*fp3;
int number;
fp1=fopen("DATA","r");
fp2=fopen("even","w");
fp3=fopen("odd","w");
printf("numbers in file are\n");
while((number=getw(fp1))!=EOF)
{
printf("%d\t",number);
}
fclose(fp1);
fp1=fopen("DATA","r");
while((number=getw(fp1))!=EOF)
{
if((number%2)==0)
{
putw(number,fp2);
}
else
{
putw(number,fp3);
}
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
fp2=fopen("even","r");
fp3=fopen("odd","r");
printf("\nnumbers in even file are\n");
while((number=getw(fp2))!=EOF)
{
printf("%d\t",number);
}
printf("\nnumbers in odd file are\n");
while((number=getw(fp3))!=EOF)
{
printf("%d\t",number);
}
fclose(fp2);
fclose(fp3);
return 0;
}
最佳答案
您正在阅读以纯文本表示的数字。
getw
读取一个机器字(例如,在我的 64 位机器上说 8 个字节),当你写出来时,它会把它写出来。这不是您想要的。
使用 fscanf
而不是 getw
来读取格式化值。
关于c - 为什么应用程序从文件中读取了不正确的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9179729/