永遠不要使用獲取!
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