fgets

Gregory Smith greg at utcsri.UUCP
Fri Apr 11 06:32:51 AEST 1986


In article <2476 at brl-smoke.ARPA> rbj at icst-cmr (Root Boy Jim) writes:
>Which brings me to another point. Fgets is worthless on binary
>data. It returns its first argument, which I already know.
>If a null is part of the data, how do you know where it stopped
>reading. Well if you're lucky, there will be a newline in there
>and that's the end of it. But if you're reading blocks of nulls,
>you're SOL. I would like fgets to return the number of chars read.
>
That's exactly what 'read' is there for, no?
Still - I agree. Even if there is  a single null in a line,
you will effectively lose everthing between that null and the next '\n'
if you read it with fgets.

I too have a question regarding fgets. fgets, as has been said, normally
stops reading at the end of a line ( after a '\n'). 
I had the following problem with EOF detection:  Suppose that the
last line in the file is "wombat soup", and this is followed by '\n' and
EOF, as is the normal case for text files. So my second-to-last call to
fgets reads "wombat soup\n" and does not set feof(infile). My last call
to fgets, however, just sets feof(infile) and returns! It didn't write
anything into the buffer. So the program saw "wombat soup\n" twice. If
the last line is *not* '\n'-terminated, the last call to fgets puts a
null-terminated "wombat soup" into the string and sets feof(infile),
which is reasonable and what I expected. So why doesn't fgets stick
a '\0' in the buffer when it sees EOF immediately? Isn't this a bug?
What I did to fix it was to set line_buffer[0]=NUL *before* calling
fgets, which is simple enough to do. Still.... grumble, grumble...

We have 4.2 BSD on vax11/780.

-- 
"If you aren't making any mistakes, you aren't doing anything".
----------------------------------------------------------------------
Greg Smith     University of Toronto      UUCP: ..utzoo!utcsri!greg



More information about the Comp.lang.c mailing list