Question

#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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top