Kraken
Kraken

Reputation: 24213

getc(fp) causing trouble

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?

Upvotes: 0

Views: 488

Answers (4)

Some programmer dude
Some programmer dude

Reputation: 409196

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.

Upvotes: 2

hmjd
hmjd

Reputation: 121971

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):
}

Upvotes: 2

unwind
unwind

Reputation: 399871

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

Upvotes: 1

DonCallisto
DonCallisto

Reputation: 29922

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

Upvotes: 0

Related Questions