Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 10 Mar 2009 18:26:34 -0400
From:      James Bailie <jimmy@mammothcheese.ca>
To:        freebsd-hackers@freebsd.org
Subject:   Re: fgetc doubts
Message-ID:  <49B6E91A.4040604@mammothcheese.ca>
In-Reply-To: <49B6DC95.9070607@FreeBSD.org>
References:  <49B6DC95.9070607@FreeBSD.org>

next in thread | previous in thread | raw e-mail | index | archive | help
fgetc() returns an int so that EOF may be distinguished from valid
return values.  Valid values are 8-bit values.  EOF is a 32-bit value.

EOF is a 32-bit two's-complement -1 (0xffffffff), and -1 input is 8-bit
two's-complement -1 (0xff).  When fgetc() casts this to an int, it
becomes 0x000000ff, or 255, and thus the two values may be distinguished
from each other.

I haven't looked at your code, but you are probably comparing EOF with
the value returned by fgetc() after it has been cast to a char.  EOF is
getting cast to a char implicitly in the comparison, so the comparison
becomes a comparison between 0xff and 0xff.  You need to test the int
returned by fgetc() for EOF before assigning it to a char.


Gábor Kövesdán wrote:
> Hello,
> 
> I have a problem when reading files with fgetc when a 0xff character 
> comes. In my code the reading stops at that point as if EOF had been 
> reached, but that's not actually the case.
> The code is here: 
> http://p4web.freebsd.org/@md=d&cd=//&c=Nsd@//depot/projects/soc2008/gabor_textproc/grep/file.c?ac=64&rev1=40 
> 
> And the problem occurs in grep_fgetln() when the buffers is being filled 
> in:
>            for (; i < bufsiz && !grep_feof(f); i++)
>                binbuf[i] = grep_fgetc(f);
> 
> Thanks in advance,
> 

-- 
James Bailie <jimmy@mammothcheese.ca>
http://www.mammothcheese.ca



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?49B6E91A.4040604>