Không bao giờ sử dụng được !!
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.
Vì vậy, có, khi fgets()
không trả lại NULL mảng điểm đến luôn luôn có một ký tự null.
Nếu fgets()
trả về NULL, mảng đích có thể đã bị thay đổi và có thể không có ký tự rỗng. Không bao giờ dựa vào mảng sau khi nhận được NULL từ fgets()
.
Sửa dụ thêm
$ 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]
$
Thấy không?no NUL in buf :)
Luôn kiểm tra giá trị trả về của 'fgets()': 'if (fgets (...) == NULL)/* không xác định mảng * /;' – pmg
Bạn có thể đúng, tuy nhiên, Tôi thấy có những câu trả lời khác cho biết '\ 0' luôn được nối thêm, ngay cả khi' fgets() 'trả về' NULL'. – Ree