C
Charlie Gordon
Ben Bacarisse said:<snip>
OK. I have always taken "it does this" to mean "... and nothing else"
but doubt has been raised about fgets and mbstowcs has an explicit
"only n chars written" clause. Do you feel that fgets is similarly
unambiguous?
7.19.7.2 The fgets function
Synopsis
1 #include <stdio.h>
char *fgets(char * restrict s, int n,
FILE * restrict stream);
Description
2 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. No
additional
characters are read after a new-line character (which is retained) or after
end-of-file. A
null character is written immediately after the last character read into the
array.
Returns
3 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.
Except in the case of a read error, the contents of the array seems pretty
well described by the above wording. fgets read characters from the stream
into the array, and then writes a null character after the last character
read. Since characters are "read into the array", you would need additional
read/write operations to move them where they belong, had they no been read
in the proper place. No such operation is described as being performed by
fgets.
The real problems with the fgets definition in the standard are:
- why is the array size specified as int instead of size_t
- what is the behaviour of fgets for n == 0, and for n < 0 ?
- will fgets return NULL or s when called with n == 1 and the stream
contains no more characters but EOF has not yet been encountered ? (I don't
think it should attempt to read any byte from the stream, and thus cannot
detect EOF, so it should return s)
- to a lesser extend, why pollute the prototype with useless restrict
keywords