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()reads in at most one less thansizecharacters from stream and stores them into the buffer pointed to bys. Reading
stops after anEOFor 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()andfgets()returnson success,andNULLon 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 returns. If the stream is at end-of-file,the end-of-file indicator for the stream shall be set andfgets()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 seterrnoto indicate the error.
这清楚地表明,如果在调用时它实际上处于EOF状态,它将仅返回NULL,即如果读取任何字节,则不会返回NULL.