Sujet : Re: Buffer contents well-defined after fgets() reaches EOF ?
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.cDate : 11. Feb 2025, 04:42:03
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20250210193511.183@kylheku.com>
References : 1 2 3 4 5 6 7 8 9 10 11
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2025-02-11, James Kuyper <
jameskuyper@alumni.caltech.edu> wrote:
What if the array is only big enough for one byte? In this case, no
characters can be read into it. Is a trailing null inserted in this case?
>
"The fgets function reads at most one less than the number of characters
specified by n from the stream pointed to by stream into the array
pointed to by s." (7.32.7.2p2)
>
If the buffer length is 1, "at most one less than the number ...
specified" is 0. Therefore, fgets() cannot read any characters into the
buffer, no matter what the contents of the input stream are. Again,
since there is no "last byte read into the array", there is no location
where a null byte should be written.
If the array consists of two bytes, then it's possible to use the fgets
function carry out the job of process input in a line-wise fashion,
using fragments of lines that are one character wide. For instance
"foo\n" may be be read in three parts "f\0", "o\0","\n\0".
If the buffer is one byte wide, then it's not possible for the loop
around fgets to meaningfully process the file.
Therefore, it might as well just return null on the first call
and every subsequent one.
It simply doesn't make sense to use an array of one byte.
A one bytea area is too small, since it can only hold a string of zero
length, and a non-zero-length file cannot be expressed as a catenation
of strings of zero length.
The fgets function /could/ null terminate always, even when returning
null, and even in the one-byte-buffer case. But what would be the point;
there is no need for code to rely on the buffer when null has been
returned.
When we use fgets, we can (and probably should) pretend that the buffer
is just a work area or context buffer for the function, and the return
value is the real data (which happens to point to the context buffer).
When we get null, the operation yielded no data. We "got something"
only when fgets returns a pointer to it.
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca