简体   繁体   中英

Why is the application reading the incorrect integers from a file?

When I try to read integers from a file, the code ends up reading different numbers than expected.

The data file contains the following numbers:

1111 111 222 333 444 555 666 777 888 -1

When I read the file, it returns the following numbers:

825307441   825307424   842150432   858993440   875836448
892679456   909522464   926365472   943208480   170994976

Why is this happening?

Relevant code:

/* 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;

  }

You are reading numbers represented in plain text.

getw reads a machine word (say 8 bytes on my 64-bit box for example), and when you write it out, it writes that out. This is not what you want.

Use fscanf instead of getw to read formatted values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM