c – fgets()的返回值

前端之家收集整理的这篇文章主要介绍了c – fgets()的返回值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚开始使用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 (‘\0‘) 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.

猜你在找的C&C++相关文章