noyuzi
noyuzi

Reputation: 41

fgetc() doesn't stop in EOF

tried to look on forums but could not reslove.

I'm trying to read from text. Text is: "To b"

But while using fgetc(), EOF is not reached, and at the end I get '\n' and then infinity 'y' samples.

Here's my code:

Node* getBinTree(FILE *fsrc){
    Node* root=NULL;
    unsigned char tmp=NULL;
    while ((tmp=fgetc(fsrc))!=EOF)
        globalArray[tmp]++;
    return root;

}

thanks a lot

Upvotes: 3

Views: 627

Answers (3)

Greg Hickman
Greg Hickman

Reputation: 41

fgetc() returns a signed integer, but your program stores the result in an unsigned char. When converting from signed to unsigned types, a negative number (EOF is often defined to be -1) becomes positive (decimal 256, in this case), so if EOF is negative, the comparison of the return value with EOF will always return false. To fix the code, change the declaration of "tmp" from an "unsigned char" to an "int".

Upvotes: 1

David Hoelzer
David Hoelzer

Reputation: 16331

The trouble you have is related to what fgetc returns. The return type is int but you are storing it into an unsigned char.

You must either change this to be an int or, as an alternative, use feof to check for an end of file condition.

Upvotes: 4

lmz
lmz

Reputation: 1580

Use int tmp. EOF can not be stored in a char because it is not a char.

Upvotes: 2

Related Questions