fseek和ftell是如何工作的?

1.fseek第一个参数是指向一个FILE文件的指针,使用fopen的时候已经打开了该文件
2.第二个参数 代表的是 偏移量,offset的值,表示从起始点开始移动的距离,而且这个参数 必须是一个long类型的值,正值代表向前移动,负值(后退),0(不动);
3,第三个参数是模式,SEEK_SET 代表文件开始;SEEK_END 代表文件的结束
SEEK_CUR 代表当前位置

#include
#include
#define SLEN 50
int main(void){
        char file[SLEN];
        char ch;
        FILE *fp;
        long count,last;
        gets(file);
        if((fp=fopen(file,"rb"))==NULL){
                fprintf(stderr,"can't open the %s\n",file);
                exit(1);
        }
        fseek(fp,0L,SEEK_END);
        last = ftell(fp);//得到fp的长度
        for(count = 1L;count<=last;count++){
                fseek(fp,-count,SEEK_END);
                ch = getc(fp);//得到该指针所对应的字符
                putchar(ch);
        }
        putchar('\n');
        return 0;
}

hello文件内容:

aaofjaojdfoajf
afoajdfoaj
afaj1

结果

111@ubuntu:~/Documents/reverse$ gcc reverse.c -o reverse
111@ubuntu:~/Documents/reverse$ ./reverse
hello
1jafa
jaofdjaofa
fjaofdjoajfoaa
111@ubuntu:~/Documents/reverse$ 

你可能感兴趣的:(fseek和ftell是如何工作的?)