加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – fgets()的返回值

发布时间:2020-12-16 04:51:21 所属栏目:百科 来源:网络整理
导读:我刚刚开始使用C中的I / O.这是我的问题 – 我有一个文件,我从中读取了我的输入.然后我使用fgets()来获取缓冲区中的字符串,我以某种方式使用它.现在,如果输入对于缓冲区来说太短,即如果fgets()的第一次读取达到EOF,会发生什么. fgets()应该返回NULL(正如我在
我刚刚开始使用C中的I / O.这是我的问题 – 我有一个文件,我从中读取了我的输入.然后我使用fgets()来获取缓冲区中的字符串,我以某种方式使用它.现在,如果输入对于缓冲区来说太短,即如果fgets()的第一次读取达到EOF,会发生什么. fgets()应该返回NULL(正如我在fgets()文档中读到的那样)?它似乎没有,我得到了正确的输入.除了我的feof(输入)并没有说我们已经达到了EOF.这是我的代码片段.
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.n",argv[argc + 1]);
    exit(EXIT_FAILURE);
}

if (output == NULL) {
    fprintf(stdout,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.n");
}
else if (ferror(input)) {
    fprintf(stdout,"Error while reading the file.n");
}

解决方法

fgets()的文档没有说出你的想法:

从我的联机帮助页

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading
stops after an EOF or a newline. If a newline is read,it is stored into the buffer. A terminating null byte (‘‘) is stored
after the last character in the buffer.

然后

gets() and fgets() return s on success,and NULL on error or when end of file occurs while no characters have been read.

我没有读到,因为说EOF将被视为错误条件并返回NULL.实际上它说只有在没有读取字符时发生EOF的情况下才会出现NULL.

POSIX标准(遵循不太容易访问的C标准)在这里:http://pubs.opengroup.org/onlinepubs/009695399/functions/fgets.html并声明:

Upon successful completion,fgets() shall return s. If the stream is at end-of-file,the end-of-file indicator for the stream shall be set and fgets() shall return a null pointer. If a read error occurs,the error indicator for the stream shall be set,fgets() shall return a null pointer,and shall set errno to indicate the error.

这清楚地表明,如果在调用时它实际上处于EOF状态,它将仅返回NULL,即如果读取任何字节,则不会返回NULL.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读