文件I/O函数:随机访问fseek()和ftell()

该程序打卡一个文件并定位到文件结尾,输出当前字符,然后向前移动知道文件开头,用ftell()函数返回当前距文件开头的位置。

/*
 * @Author: Your name
 * @Date:   2020-03-15 21:32:33
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-03-17 20:36:33
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SLEN 81
#define CNL_Z '\032'
int main()
{
    char file[SLEN];
    char ch;
    FILE *fp;
    long count,last;
    puts("Enter the number of the file to be processed:");
    scanf("%80s",file);
    if((fp=fopen(file,"rb"))==NULL)
    {
        printf("reverse can't open %s\n",file);
        exit(EXIT_FAILURE);
    }
    fseek(fp,0L,SEEK_END);//定位到文件结尾
    last = ftell(fp);//查看从文件开头到文件结尾有多少字节数
    for(count = 1;count<=last;count++)
    {
        ch = getc(fp);
        fseek(fp,-count,SEEK_END);//从末尾依次获取字符
        putchar(ch);
    }
    putchar('\n');
    fclose(fp);
    getchar();
    return 0;
}

分析:

fseek(fp,0L,SEEK_END);

把当前位置设置为距文件末尾0字节偏移量,也就是说把当前位置设置在文件的末尾,下一条语句:

last = ftell(fp);

把从文件开始处到文件结尾的字节数赋给last.
然后是一个for循环:

 for(count = 1;count<=last;count++)
    {
        ch = getc(fp);
        fseek(fp,-count,SEEK_END);//从末尾依次获取字符
        putchar(ch);
    }

第一轮迭代把程序定位到文件结尾的第一个字符(即,文件的最后一个字符)。然后,程序打印该字符。下一轮迭代把程序定位到前一个字符,并打印该字符。重复这一过程直到到达文件的第一个字符,并打印。

下面介绍fseek()ftell()函数:
文件I/O函数:ftell()
文件I/O函数:fseek()

发布了84 篇原创文章 · 获赞 18 · 访问量 5805

猜你喜欢

转载自blog.csdn.net/qq_44486550/article/details/104930704