Write file with int[10] without ‘ ’ or ‘\n’, When I read it, there is something wrong?

StackOverflow https://stackoverflow.com/questions/20308353

  •  06-08-2022
  •  | 
  •  

Frage

#define MAXN 1000000
FILE *fp1;
fp1 = fopen("num.txt", "w");
for(int i=0; i<MAXN; i++) {
    int a = rand() % (MAXN/10);
    fprintf(fp1, "%d", a);
}
...
FILE *fp2;
fp2 = fopen("num.txt", "r");
int a;
fscanf(fp2, "%d", &a);
printf("%d", a);

when I create a file, and fopen it to fp.

and I read it with fread, and I got the wrong num

(such as the first num 6414, and I got num -1182340738)

And I write it with '\n' or ' ' there is no error.

War es hilfreich?

Lösung

There doesn't appear to be a character separating the numbers, how does your parser know when one number ends and the next starts?

This I guess is your problem, it's thinking it's one very big number and overflowing to negative.

Andere Tipps

If your add \n,the file buffer will flush,but without \n it will not flush, so you should close first fp1 before you open the fp2.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top