/*以下程序的功能是:实现从键盘输入字符,存入文件d:\\fseekin.txt,并将其反写到d:\\fseekout.txt*/#include<stdio.h>#include<string.h>int main(int argc,char * argv[]){FILE * fpin,* fpout;int i=0;int j=0;char ch;if((fpin=fopen("d:\\fseekin.txt","w+"))==NULL)//*注意!不能写成"w",因为后面还要读!{printf("打开文件\"d:\\fseekin.txt\"时出错!\n");getchar();return 0;}if((fpout=fopen("d:\\fseekout.txt","w+"))==NULL){printf("打开文件\"d:\\fseekout.txt\"时出错!\n");getchar();return 0;}printf("请输入一组字符串并以#号结束:\n");//*下面while语句的功能实现从显示器接受字符,输入到文件d:\\fseekin.txt中while((ch=fgetc(stdin))!='#'){fprintf(fpin,"%c",ch);i++; //*记住输入文件的字符数} fprintf(stdout,"刚才输入的%d个字符使\"d:\\fseekin.txt\"的文件指针向前移动了%d个字节\n",i,ftell(fpin));j=ftell(fpin);printf("fpin中指针偏移%d个字节\n",j);i=1;/*重新初始化i,为下面的循环做准备//*下面while 语句的功能实现将d:\\fseekin.txt的所有字符反写到d:\\fseekout.txtwhile(ftell(fpin)!=0&&ftell(fpin)!=-1&&i<=j)//* 为什么不能用for(i=1;i<=j;i++)?好 像用了之后就只能倒置一半的字符!{ fseek(fpin,-i,2);fputc(fgetc(fpin),fpout);i++;}//*下面的语句测试并关闭打开的文件if(fclose(fpin)||fclose(fpout)){printf("关闭文件\"d:\\fseekin.txt\"或\"d:\\fseekout.txt\"时出错!\n");getchar();return 0;}printf("关闭文件成功!\n");getchar();return 0;}我的问题是为什么将第二个while语句即while(ftell(fpin)!=0&&ftell(fpin)!=-1&&i<=j){ fseek(fpin,-i,2);fputc(fgetc(fpin),fpout);i++;}该为:for(i=1;i<=j;i++){ fseek(fpin,-i,2);fputc(fgetc(fpin),fpout);i++;}
1 回答

守着一只汪
TA贡献1872条经验 获得超4个赞
for(i=1;i<=j;i++)
{
fseek(fpin,-i,2);
fputc(fgetc(fpin),fpout);
i++;
}
每次i自加两次,当然提前了,而且是隔位的,循环体内i++删了
- 1 回答
- 0 关注
- 139 浏览
添加回答
举报
0/150
提交
取消