Csharp_learner
Csharp_learner

Reputation: 341

C programming : End of file - operation

I am trying to check while not end of file in c programming.

Can anyone please help, I am not able to understand what is that I am doing wrong in following code. It prints the last set of rows twice.

/* Reads the Input file. */
fp = fopen("matrix_p2.txt","r");
if(fp == NULL)
{
    printf("*** ERROR: Could not open file matrix_p2.txt\n");
}

p = 2;
while(!feof(fp))
{
    printf("n= %d, m= %d", n,m);

    for(i = n; i < N/p; i++)
        for(j = m; j < M; j++)
            fscanf(fp, "%d",&(A[i][j]));

    print_blk(A, n, m, N/p, M);
    //n = n + N/p;

    size[0] = N;
    size[1] = M;
}

fclose(fp);

INPUT:

1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7

OUTPUT:

1 2 3 4
2 3 4 5

3 4 5 6
4 5 6 7

3 4 5 6
4 5 6 7

But I want output as followS:

OUTPUT

1 2 3 4
2 3 4 5

3 4 5 6
4 5 6 7

Upvotes: 2

Views: 10528

Answers (1)

ruakh
ruakh

Reputation: 183211

That's simply how feof works; it doesn't tell you if you're about to hit end-of-file, it tells you if you have hit end-of-file. (That is: it doesn't tell you when you've read the last character; it tells you when you've read past the last character.) The simplest solution is to change this:

        while(!feof(fp))

to this:

        while(1)

and this:

            for(i = n; i < N/p; i++)
                for(j = m; j < M; j++)
                    fscanf(fp, "%d",&(A[i][j]));

to this:

            for(i = n; i < N/p; i++)
                for(j = m; j < M; j++)
                    fscanf(fp, "%d",&(A[i][j]));
            if(feof(fp))
                break; // hit end-of-file while getting the array

so that you test for end-of-file after you've read in the array (or haven't) and before you do anything with it.

(It would be even better, though, to actually examine the return-value of fscanf and handle any error conditions such as end-of-file.)

Upvotes: 4

Related Questions