0

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?

2
  • 2
    don't forget to check fopen() return value Feb 21, 2012 at 13:14
  • and do not forget the fclose() Feb 21, 2012 at 15:27

4 Answers 4

2

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.

1
  • this is the most-seen solution in C Feb 21, 2012 at 15:26
2

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):
}
2
  • This does not fix the problem that a has the wrong type (char instead of int)... Feb 21, 2012 at 15:56
  • Yes, but just in hopes of getting OP to notice the correct answer below before blindly accepting something. Removed it now. Feb 21, 2012 at 16:15
1

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

0

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

1
  • This will run through the loop at least once, and still print -1 if fgetc returns EOF immediately. Feb 21, 2012 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.