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?

hmjd
  • 120,187
  • 20
  • 207
  • 252
Kraken
  • 23,393
  • 37
  • 102
  • 162

4 Answers4

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):
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
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.

unwind
  • 391,730
  • 64
  • 469
  • 606
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

DonCallisto
  • 29,419
  • 9
  • 72
  • 100