कभी भी उपयोग नहीं होता !!
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()
शून्य गंतव्य सरणी वापस नहीं करता है हमेशा एक अशक्त चरित्र है।
यदि fgets()
शून्य लौटाता है, तो गंतव्य सरणी बदल दी गई हो सकती है और इसमें कोई शून्य चरित्र नहीं हो सकता है। fgets()
से न्यूल प्राप्त करने के बाद कभी भी सरणी पर भरोसा न करें।
संपादित उदाहरण
$ 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]
$
देखें जोड़ा?buf में कोई एनयूएल नहीं :)
हमेशा 'fgets की वापसी मान) की जांच (': 'अगर (fgets (...) == शून्य)/* अनिश्चित सरणी * /;' – pmg
आप सही हो सकता है, तथापि, मैं देखता हूं कि '\ 0' हमेशा बताए गए अन्य उत्तरों हैं, भले ही' fgets() '' NULL 'लौटाए। – Ree