fseek函数是 用来设定文件的当前读写位置.
函数原型: int fseek(FILE *fp,long offset,int origin);
函数功能:把fp的文件读写位置指针移到指定的位置.
fseek(fp,20,SEEK_SET); 意思是把fp文件读写位置指针从文件开始后移20个字节.
ftell函数是用来获取文件的当前读写位置;
函数原型: long ftell(FILE *fp)
函数功能:得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.
ban=ftell(fp); 是获取fp指定的文件的当前读写位置,并将其值传给变量ban.
fseek函数与ftell函数综合应用:
分析:可以用fseek函数把位置指针移到文件尾,再用ftell函数获得这时位置指针距文件头的字节数,这个字节数就是文件的长度.
/* ************************************************************************ * Filename: test.c * Description: * Version: 1.0 * Created: 2011年07月21日 23时26分08秒 * Revision: none * Compiler: gcc * Author: YOUR NAME (), * Company: 用于计算文件的大小 * ************************************************************************/ #include <stdio.h> int main(int argc, char *argv[]) { int filesize; FILE *fp = fopen("hello.txt","rb"); if(fp == NULL) { perror("open error"); return -1; } fseek(fp,0,SEEK_END); filesize = ftell(fp); printf("this file size is:%d byte!\n",filesize); fclose(fp); return 0; }