永远不要使用获取!
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.
所以,是,当fgets()
不返回NULL目标数组总是有一个空字符。
如果fgets()
返回NULL,则目标数组可能已被更改并且可能没有空字符。在从fgets()
获得NULL之后,千万不要依赖数组。
编辑例如添加
$ cat fgets_error.c
#include <stdio.h>
void print_buf(char *buf, size_t len) {
int k;
printf("%02X", buf[0]);
for (k=1; k<len; k++) printf(" %02X", buf[k]);
}
int main(void) {
char buf[3] = {1, 1, 1};
char *r;
printf("Enter CTRL+D: ");
fflush(stdout);
r = fgets(buf, sizeof buf, stdin);
printf("\nfgets returned %p, buf has [", (void*)r);
print_buf(buf, sizeof buf);
printf("]\n");
return 0;
}
$ ./a.out
Enter CTRL+D:
fgets returned (nil), buf has [01 01 01]
$
看到了吗?没有NUL buf :)
来源
2009-11-02 09:42:36
pmg
经常检查'与fgets的返回值()':'如果(与fgets(...)== NULL)/ *不确定的数组* /;' – pmg 2009-11-02 10:15:43
你可能是正确的,但是,我发现还有其他答案指出总是附加'\ 0',即使'fgets()'返回NULL。 – Ree 2009-11-02 10:26:06