Sujet : Re: Buffer contents well-defined after fgets() reaches EOF ?
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.cDate : 09. Feb 2025, 07:23:33
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20250208220533.551@kylheku.com>
References : 1
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2025-02-09, Janis Papanagnou <janis_papanagnou+
ng@hotmail.com> wrote:
To get the last line of a text file I'm using
>
char buf[BUFSIZ];
while (fgets (buf, BUFSIZ, fd) != NULL)
; // read to last line
>
If the end of the file is reached my test shows that the previous
contents of 'buf' are still existing (not cleared or overwritten).
Whenever fgets successfully reads one or more characters, and
adds them to the array (followed by a null terminator), it
returns the pointer it was given.
fgets only returns null when:
- it hits EOF when trying to obtain the first character.
- it hits an I/O error.
But the man page does not say anything whether this is guaranteed;
it says: "Reading stops after an EOF or a newline.", but it says
nothing about [not] writing to or [not] resetting the buffer.
But of course, ISO C has the requirements nailed down. e.g. C99:
"The fgets function returns s if successful. If end-of-file is
encountered and no characters have been read into the array, the
contents of the array remain unchanged and a null pointer is returned.
If a read error occurs during the operation, the array contents are
indeterminate and a null pointer is returned."
Beware of man pages identifying themselves as "Linux Programmer's
Manual". Their quality is all over the place, and rarely hits
a high note.
Is that simple construct safe to get the last line of a text file?
While fgets returns a pointer, you have a good line of input.
The terminating newline is included, unless it's the last line
and the file is missing it.
Some C newbies make this mistake:
while (!feof(stdin)) {
fgets(...)
/* process line */
}
their code ends up processing the last line twice. On the last byte
of input, which is usually the terminating newline of the last line,
fgets returns without having reached EOF. The loop spins around one more
time. This time fgets returns NULL, not having read a single byte. The
code doesn't check this and processes the buffer again.
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca