为什么应用程序从文件中读取不正确的整数?

时间:2012-02-07 16:16:03

标签: c

当我尝试从文件中读取整数时,代码最终会读取与预期不同的数字。

数据文件包含以下数字:

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;

  }

1 个答案:

答案 0 :(得分:6)

您正在阅读以纯文本格式表示的数字。

getw读取机器字(例如我的64位盒子上的8个字节),当你把它写出来时,它会写出来。这不是你想要的。

使用fscanf代替getw来阅读格式化值。