fgets() 的返回值 [英] Return value of fgets()
问题描述
我最近刚刚开始在 C
中使用 I/O
.这是我的问题 -
我有一个文件,我从中读取了我的输入.然后我使用 fgets()
在我以某种方式利用的缓冲区中获取字符串.现在,如果输入对于缓冲区来说太短会发生什么,即如果 fgets()
的第一次读取到达 EOF
.fgets()
是否应该返回 NULL
(正如我在 fgets()
文档中所读到的)?似乎没有,我正确地得到了我的输入.此外,即使我的 feof(input)
也没有说我们已经达到了 EOF
.
这是我的代码片段.
I have just recently started working with I/O
in C
. Here is my question -
I have a file, from which I read my input. Then I use fgets()
to get strings in a buffer which I utilise in some way. Now, what happens if the input is too short for the buffer i.e. if the first read by fgets()
reaches EOF
. Should fgets()
return NULL
(as I have read in fgets()
documentation)? It seems that it doesn't and I get my input properly. Besides even my feof(input)
does not say that we have reached EOF
.
Here is my code snippet.
char buf[BUFSIZ];
FILE *input,
*output;
input = fopen(argv[--argc], "r");
output = fopen(argv[--argc], "w");
/**
* If either of the input or output were unable to be opened
* we exit
*/
if (input == NULL) {
fprintf(stdout, "Failed to open file - %s.
", argv[argc + 1]);
exit(EXIT_FAILURE);
}
if (output == NULL) {
fprintf(stdout, "Failed to open file - %s.
", argv[argc + 0]);
exit(EXIT_FAILURE);
}
if (fgets(buf, sizeof(buf), input) != NULL) {
....
}
/**
* After the fgets() condition exits it is because, either -
* 1) The EOF was reached.
* 2) There is a read error.
*/
if (feof(input)) {
fprintf(stdout, "Reached EOF.
");
}
else if (ferror(input)) {
fprintf(stdout, "Error while reading the file.
");
}
推荐答案
fgets()
的文档并没有说明你的想法:
The documentation for fgets()
does not say what you think it does:
来自我的手册页
fgets()
从流中读取至多小于 size
个字符,并将它们存储到 s
指向的缓冲区中.阅读在 EOF
或换行符后停止.如果读取换行符,则将其存储到缓冲区中.存储终止空字节 ('