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, 13:04:22
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20250211034010.100@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, Andrey Tarasevich <
noone@noone.net> wrote:
If by that you mean, "what if the value of 1 is passed as second
argument", then, as I stated in one of my previous messages:
>
No attempt to read anything from the stream is made, which means that
end-of-file or I/O error conditions do not arise (unless, perhaps, the
stream was already in error condition) and the [0] byte of the buffer is
simply set to '\0'.
ISO C: "If a read error occurs during the operation, the members of the
array have unspecified values and a null pointer is returned."
(I think that stretches to the situation when the error has happened
already, but clearerr(stream) has not been called to remove the
condition.)
Whenever fgets returns null due to not being able to read any characters
into the array, it should not change the value of the elements of the
array, even if the reason is that the array hos no room.
We can think about the possibility of fgets returning a pointer
to a null string when an array of size 1 is uzed, without advancing
the stream.
I find it not so easy to argue that it would not be /conforming/. The
behavior can be regarded as a straightforward special case of the
ordinary behavior, when fgets adds one or more characters to the array,
runs out of room, and then null terminates and exits.
I find it easy to argue that it's anything but a bad idea for fgets to
ever return an empty string.
The way fgets is defined, it provides single clear termination signal
for loops; the null pointer.
If an implementation of fgets may return an empty string (only
conceivably allowed in the size 1 array case), then that constitutes an
additional new termination signal. A program not looking for this
additional termination signal shall loop indefinitely over a finite
stream.
While in that situation, the implementation might be conforming, and be
processing a strictly conforming program, even if so, the infinite
looping is a needlessly poor situation which can be avoided by not
taking that interpretation: i.e. if no characters are added to the array
for any reason, then have fgets always return NULL, rather than an empty
string.
It would be a good idea to add the requirement "fgets shall not
return a pointer to an empty string" to its description to codify that.
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca