请教一个fgets函数的疑问
FIO37-C. 不要假设fgets()在执行成功时一定会返回一个非空字符串
最典型的情况就是以“二进制模式”访问文件时,完全有可能读取到一行的内容的第一个字符就是一个null字符。
~~~~~~~~~~~~~~~~什么情况下,fgets返回成功,内容的第一个字符就是一个null字符??
【 在 sunshot 的大作中提到: 】
你的结果有错是因为
ccc 34多了一个回车换行 \n
没有\n,程序运行就是对的,测试了一下:并总结前面几位的答案
char *fgets( char *str, int num, FILE *stream );
The function fgets() reads up to num - 1 characters from the given file stream and dumps them into str. fgets() will stop when it reaches the end of a line, in which case str will be terminated with a newline. If fgets() reaches num - 1 characters or encounters the EOF, str will be null-terminated. fgets() returns str on success, and NULL on an error.
如果文件末尾有一个空行,注意特别注意用fgets进行读,比如文件:
aaa 234 444 bbb
123 kkk 9 00 00000 0000
ccc 34
如果最后没有空行,即没有\n,读到ccc 34这行时,fgets遇到了EOF,结束,str="ccc 34\0"; 如果最后有空行;读到ccc 34这行时,fgets遇到了new line,str="ccc 34\n\0",此时文件未返回EOF,再次fgets时,遇到EOF,fgets返回NULL,str的内容没有变,因此用fgets读时判断是否该结束最好如此:
while(fgets(...)) {
...
}
而不要用
while(!feof()) {
fgets();
...
}
用第二种方式,将A文件copy到B文件中,如果A文件末尾有\n,则新文件会增加一行,增加的行为A文件的倒数第二行,即最后一个\n之前的那行。
【 在 WWTWW ( Nothing last forever) 的大作中提到: 】
: 标 题: fgets怎么判断文件末尾?
: 发信站: 水木社区 (Sun Jul 9 16:22:50 2006), 站内
:
: 想把一个文件的每行读出来,cp到另外一个文件中,用feof()判断文件末尾的时候,最后一行总是要输出两次,该怎么解决阿?fcanf可以用返回值来判断,可是fgets返回的是数组的首地址,不知道该怎么判断了,当文件的行不规则的时候,也无法用多个fscanf来读多个数据阿。
: test.txt like this
: *********
: aaa 234 444 bbb
: 123 kkk 9 00 00000 0000
: ccc 34
: ************
: the source code like this
: ************
: #include<stdio.h>
: #include<stdlib.h>
: int main(int argc,char *argv[])
: { FILE *infp,*outfp;
: char line[200];
: int i=0;
: infp=fopen(argv[1],"r");
: outfp=fopen(argv[2],"w");
: while(!feof(infp)){
: fgets(line,200,infp);
: i++;
: fputs(line,outfp);
: printf("totally %d lines have been output\n",i);
: }
: fclose(infp);
: fclose(outfp);
: }
: ./testgets test.txt output.txt
: 输出结果是
: aaa 234 444 bbb
: 123 kkk 9 00 00000 0000
: ccc 34
: ccc 34
: 好像用feof判断末尾的时候,总会有类似的状况,有对应的解决办法么?谢谢!
: --
:
: ※ 来源:·水木社区
http://newsmth.net·[FROM: 218.249.67.*]
--
FROM 218.66.91.*