Re: Behavior of feof()

Harald Koenig (koenig@tat.physik.uni-tuebingen.de)
Sat, 22 Feb 1997 15:19:27 +0100 (MET)


> I've just encountered a very odd behavior of feof(); on
> linux-2.0.29. In the following program:

your use of fscanf() is completely broken!
have you ever tried to check what is read/written (either check the output
or using strace) or even the retiurn value of fscanf() (which will tell you
how many items are scanned and written to arguments) ??

> fscanf(rgb,"%d%d%d%s",&r,&g,&b,cname);

tries to read a decimal number first.

the first lines in my rgb.txt is

! $XConsortium: rgb.txt,v 10.41 94/02/20 18:39:36 rws Exp $
255 250 250 snow
248 248 255 ghost white
248 248 255 GhostWhite

so fscanf will try to convert '!' to a decimal, which fails.
thus no more scanning is done, fscanf returns 0 (zero) and no more
characters are read; '!' is still the first character.
the next call to fscanf will try to convert '!' to a decimal ...

removing that first line and trying again shows that the "snow" entry
is correctly scanned and output, but for the 3rd line cname will get
"ghost" (which is the next string in the input stream; NOTE: strings are
terminated by white space!!). now 'w' of "white" is the first character
in the input stream. the next fscanf call will try to convert 'w' to a decimal,
which fails...

summary:
a) check return values !!
b) (almost) never ever use fscanf() (or be *very* sure about your format)

a possible solution would be:

char line[80];

while (!feof(rgb)) {
fgets(rgb, 80, line);
if (4 == sscanf(rgb,"%d%d%d%[^\n"]",&r,&g,&b,cname)) {
output new entry ...
}
}

or just

while (fgets(rgb, 80, line) != EOF) ....

Harald

--
All SCSI disks will from now on                     ___       _____
be required to send an email notice                0--,|    /OOOOOOO\
24 hours prior to complete hardware failure!      <_/  /  /OOOOOOOOOOO\
                                                    \  \/OOOOOOOOOOOOOOO\
                                                      \ OOOOOOOOOOOOOOOOO|//
Harald Koenig,                                         \/\/\/\/\/\/\/\/\/
Inst.f.Theoret.Astrophysik                              //  /     \\  \
koenig@tat.physik.uni-tuebingen.de                     ^^^^^       ^^^^^