提问人:Zi Elad 提问时间:8/3/2019 更新时间:8/3/2019 访问量:128
为什么这个条件没有捕获 EOF?我得到分段错误 [重复]
Why this while condition doesn't catch EOF? and i get segmentation fault [duplicate]
问:
所以问题是,我尝试使用 fgets 从文本中读取一行并将其打印出来,但它效果不佳,它完美地读取所有文件直到最后,但它读取最后一行两次,而不是“喊”出错。
void somefun(FILE *file){
char *buf[81];
while(!feof(file)){
if(fgets(buf,80,file)){
continue;}
printf("%s,buf); }
void main() {
FILE *fp;
fp=fopen("somefile.txt","r+");
somefun(fp); }
答:
0赞
alk
8/3/2019
#1
完全没有必要使用。feof()
它可能看起来像这样:
#include <stdio.h>
void somefun(FILE* file) {
char buf[80];
while (NULL != fgets(buf, 80, file)) {
printf("%s", buf);
}
if (ferror(file)) {
fprintf(stderr, "fgets() failed\n");
}
}
int main(void) {
FILE *fp = fopen("somefile.txt", "r+");
if (NULL == fp) {
fprintf(stderr, "fopen() failed\n");
}
else {
somefun(fp);
}
}
评论
feof()
buf
char *
char
fgets()
buf
fgets()
fgets()
feof()
main()
int
void
!feof
buf
if
continue
while(fgets(buf,80,file)) printf("%s",buf);