关于反向输出文件内容原始代码遇到了一些问题,光标在屏幕上一直不停闪烁。
原始代码如下
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char name[10],c;
printf("Input the filename you want to open:");
scanf("%s",name);
if(fp=fopen(name,"r")==NULL)
{
printf("Cannot open this file.\n");
exit(0);
}
fseek(fp,0,2);
printf("The reversed string is:");
while(ftell(fp)!=0)
{
c=fgetc(fp);
putchar(c);
fseek(fp,-1L,1);
}
fclose(fp);
return 0;
}
李老师给出建议:执行fgetc时指针在移动,可参见ppt中的案例讲解,为什么可以依次输入是个字符? 与fseek结合时要小心。请先自己体会下。
以及修改后的代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char name[10],c;
printf("Input the filename you want to open:");
scanf("%s",name);
if((fp=fopen(name,"r"))==NULL)
{
printf("Cannot open this file.\n");
exit(0);
}
fseek(fp,0,2);
printf("The reversed string is:\n");
int value=ftell(fp);
while(value!=0)
{
c=fgetc(fp);
putchar(c);
fseek(fp,-2L,1);
value-=1;
}
fclose(fp);
return 0;
}
fopen中加上了():(fp=fopen(name,”r”))==NULL,如果不加()就会出现warning: assignment makes pointer from integer without a cast.且程序无法正常运行。
第二个fseek中-1L被改为-2L:fgetc函数在读取字符时,光标始终向后移,每读取一个字符指针向后移动一个字符,所以使用fseek时,需要将读写标记向前移动两个字节的位置。
fseek()函数一般用于二进制文件。在文本文件中,由于要进行转换,故计算的位置往往会计算不准。
ftell使用了value来做中介:函数 ftell 用于得到文件位置指针当前位置相对于文件首的偏移字节数。该函数对大于231-1文件,即:2.1G以上的文件操作时可能出错。
文件读写标记类似于光标,当处于2时,即文件末尾,相当于光标在右侧;当处于文件开头时,光标在左侧。