|
这是一个显示文件内容的小程序,其中用了两种方法:
-------------------
/*readf.c*/
[code:1]
#include <stdio.h>
#define len 11
int main(int argc,char **argv)
{
int line,position,a;
char c=0;
char arg[len];
line=position=a=0;
if(argc<2){ printf("please enter file name\n"); exit(1);}
FILE *fp=fopen(argv[1],"r");
/*-----第一种方法-------*/
while(c!=EOF){
c=fgetc(fp);/*每次读一个字符*/
putchar(c);
}
printf("\n");
/*-----再把全部字符的ascii码编号打出来--*/
rewind(fp);
c=0;
while(c!=-1)
{
c=fgetc(fp);
printf("%d,",c);
}
printf("\n");
/*--------第二种方法------*/
rewind(fp);
while(!(feof(fp)||ferror(fp)))
{
fgets(arg,len,fp);/*每次读长度为len的串*/
while(a<len-1)
{
if(arg[a++]=='\12')
{
line++;position+=a;
printf("%s line:%d,lenth:%d\n",arg,line,position);/*在每行结尾显示行号和长度*/
position=0;
a=len;
break;
}
}
if((a==len-1)&&!feof(fp))
{
position+=len-1;
printf("%s",arg);
}
a=0;
}
fclose(fp);
}
[/code:1]
-------------------------
编译后执行:
bash-2.05b# ./readf file1
1dfdsgadsgfdsgdgsg
2dffsdfsdafdsfas
3asdfasdfsdfdsfdsf
4sdafdsfsddfdfdseedffsg
gfhjg
49,100,102,100,115,103,97,100,115,103,102,100,115,103,100,103,115,
103,10,50,100,102,102,115,100,102,115,100,97,102,100,115,102,97,
115,10,51,97,115,100,102,97,115,100,102,115,100,102,100,115,102,
100,115,102,10,52,115,100,97,102,100,115,102,115,100,100,102,100,
102,100,115,101,101,100,102,102,115,103,10,103,102,104,106,103,10,-1,
1dfdsgadsgfdsgdgsg
line:1,lenth:19
2dffsdfsdafdsfas
line:2,lenth:17
3asdfasdfsdfdsfdsf
line:3,lenth:19
4sdafdsfsddfdfdseedffsg
line:4,lenth:24
gfhjg
line:5,lenth:6
gfhjg
line:6,lenth:6
其实文件只有5行,第1种方法没有问题,但第2种方法里打出了6行.将最后一行重复了.
用gdb跟踪,发现读到文件末尾处时,循环回到while(!(feof(fp)||ferror(fp)))
并没有停止,而是继续了一个循环,把最后一次读的字符串重新打了一次.
大家说这是为什么呢?请指教. |
|