Return to BSD News archive
Path: euryale.cc.adfa.oz.au!newshost.anu.edu.au!harbinger.cc.monash.edu.au!news.mira.net.au!inquo!in-news.erinet.com!imci5!imci4!newsfeed.internetmci.com!btnet!zetnet.co.uk!dispatch.news.demon.net!demon!microl4.microlise.UUCP!news
From: andrewg@microlise.co.uk (Andrew Gierth)
Newsgroups: comp.unix.bsd.misc,alt.unix.wizards,comp.unix.misc
Subject: Re: How to write end of file character into file??!
Date: 24 Apr 1996 18:08:10 GMT
Organization: Microlise Engineering Ltd.
Lines: 54
Message-ID: <4llqma$71u@microl4.microlise.UUCP>
References: <xsvarshney-0604962038290001@newshub.csu.net> <4ktvmc$5d6@is05.micron.net> <4kuonh$q2@anorak.coverform.lan> <4l5le1$amd@is05.micron.net> <4l85m7$fjs@sv024.SanDiegoCA.ATTGIS.COM> <4lg9i8$8if@is05.micron.net>
Reply-To: andrewg@microlise.co.uk (Andrew Gierth)
NNTP-Posting-Host: andrewg.microlise.uucp
X-NNTP-Posting-Host: microl.demon.co.uk
X-Newsreader: IBM NewsReader/2 v1.2
Xref: euryale.cc.adfa.oz.au comp.unix.bsd.misc:838 alt.unix.wizards:3718 comp.unix.misc:22213
In <4lg9i8$8if@is05.micron.net>, dwight@micron.net (Dwight Tovey) writes:
[previous context snipped]
>At any rate, what I was trying to point out (possibly not very well) is that
>testing for the EOF "value" can cause problems. I have seen code similar to the
>following:
[code snipped - others have already commented on it]
>However the following
>code will go to the "real" end of the file for both binary and text files:
>
> char ch;
> FILE *fp
>
> fp = fopen( "foo", "r" );
> while( !feof( fp )) {
> ch = fgetc(fp);
> putchar( ch );
> }
>
>Once again, I don't claim that the code I am showing here is the "best" way to do
>anything. My only intention is to point out that testing for the "EOF character"
>on a read can lead to confusion when you get a file that has non-text data.
It certainly is not the best way! It is not even a correct way. You
have conclusively proved that it is just as easy to get confused about
end-of-file when using feof() as when using fgetc().
Observe the final iteration of your loop:
feof(fp) returns false
fgetc(fp) returns EOF
(char)EOF stored into ch
putchar(ch) writes (char)EOF to stdout (y-umlaut if using ISO8859/1)
feof(fp) returns true; loop exits.
Remember, feof() returns true only *after* you have attempted to
read past the end-of-file.
>FWIW: I have worked in Unix for more than a few years, including porting Unix
>kernel & library routines to different platforms. I still don't claim to be an
>"expert" at anything, but I do have a passing familiarity with some of it.
> /dwight
I hope you regard this as an opportunity to improve on your
'passing familiarity'. This is (amongst others) alt.unix.WIZARDS,
after all...
-- Andrew (andrewg@microlise.co.uk)
"How is this place run - is it an anarchy?"
"No, I wouldn't say so; it is not that well organised..."