看到书中讲解,fgets()函数在读到文件结尾的时候,或者 读取错误的时候返回 NULL。 但是,这里的 读到文件结尾到底是什么意思?
例如下面的程序:
#include<stdio.h>
#define LENG 100
#define CHANG 20
int main(void)
{
char words[LENG];
FILE *fp;
char *ptr;
int num,i=0;
fp=fopen("1221-1.txt","a+");
ptr=fgets(words, CHANG,fp);
printf("the ptr is %d.\n",*ptr);
fputs(words,stdout);
fclose(fp);
return 0;
}
比如上面的程序, 文件中只在开始处 包含 5个a, , 这样 fgets是可以读到结尾的,但是返回值并不是NULL, 而是字符数组的首地址。
能不能讲的 透彻 清晰一点,到底什么时候 返回NULL。
这个问题分几种情况:
1、读取的首字母如果不为空,则顺序读取指定长度字符,如果读取导致文件到达尾部则返回文件中剩余的字符;
2、如果读取前文件已经到达尾部,则返回NULL,而且读取的字符数组内容不变,这种情况就是你的问题题目问的情况“到底什么时候返回NULL”;
3、如果发生其他错误,则会产生不可预知后果,此处由异常处理捕获。
有帮助请采纳,谢谢!
就是读完了5个字符之后,再调用一次fgets就读到文件末尾了
https://en.cppreference.com/w/c/io/fgets
str on success, null pointer on failure.
If the end-of-file condition is encountered, sets the eof indicator on stream (see feof()). This is only a failure if it causes no bytes to be read, in which case a null pointer is returned and the contents of the array pointed to by str are not altered (i.e. the first byte is not overwritten with a null character).
If the failure has been caused by some other error, sets the error indicator (see ferror()) on stream. The contents of the array pointed to by str are indeterminate (it may not even be null-terminated).