Question

Here is my code.

#include<stdlib.h>
#include<stdio.h>
int main(int argc,char** argv)
{
    char a;
    a=9;
    FILE * fp;
    fp=fopen(argv[1],"r");
    while(a!= EOF)
    {
        a=fgetc(fp);
        printf("\n%d",a);
    }
}

The output to this is alright but at the end I am getting a weird character with -1 (since I am printing integer value.

How to stop it at EOF only? Also what is this character?

Was it helpful?

Solution

Besides the methods in the other answers, you can also do like this:

while ((a = fgetc(fp)) != EOF)
{
    printf("%d\n", a);
}

Now you have a few alternative solutions. :)

Edit: As R.. so kindly reminds us, you also have to change the type of a to int.

OTHER TIPS

You are printing the EOF character (the -1) as you do not check if EOF was encountered immediately after fgetc(). Change the structure of the loop to:

int a; /* not char, as pointed out by R... */

for (;;)
{
    a = fgetc(fp);
    if (EOF == a) break;
    printf("\n%d", a):
}

You need to make a have type int, as that type is the return type of fgetc(), and is needed to represent EOF correctly.

Why don't you stop the while with this condition:

do {...}while(a != EOF)

I suppose that a got EOF value AFTER read it. So, you do the cycle an extra time

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