反向输出文件内容

关于反向输出文件内容原始代码遇到了一些问题,光标在屏幕上一直不停闪烁。
原始代码如下

#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时,即文件末尾,相当于光标在右侧;当处于文件开头时,光标在左侧。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值