0

I've just started with FILE I/O today, and I'm confused here. The while loop in the code below gives a weird output. It prints i starting from i = 1, and then a[1] = .. But outside the while loop, I've specified i = 0. Any reason for why i is incrementing to 1 after entering the while loop? The confusing thing though is that the final for loop, is printing a[0] = 0 correctly!

#include <stdio.h>
#include <stdlib.h>
#define N 11

int main()
{
    FILE *fp;
    int i, a[N];
    fp = fopen("numbers.txt", "w");
    for(i = 0; i < N; i++)
    fprintf(fp,"%d\n",i);
    fclose(fp);
    fp = fopen("numbers.txt", "r");
    i = 0;
    while(!feof(fp))
    {
        printf("i = %d ",i);
        fscanf(fp,"%d",&a[i]);
        printf("a[%d] = %d\n",i,a[i]);
        i++;
    }
    for(i = 0; i < N; i++)
    printf("%d\n",a[i]);
    return 0;
}

EDIT: Got the above issue clarified, another confusion now. After reading the last number in the file, shouldn't the feof(fp) return a non-zero value and thus terminate the while loop? Why is it executing the loop one extra time?

4

1 回答 1

1

Your terminal cuts off the first line of the output because it's too long.

于 2013-02-21T17:33:19.150 回答