相关函数:rewind, ftell, fgetpos, fsetpos, lseek
头文件:#include <stdio.h>
fseek函数是用来设定文件的当前读写位置:
定义函数:int fseek(FILE * stream, long offset, int whence);
函数说明: fseek()用来移动文件流的读写位置.
1、参数stream 为已打开的文件指针,
2、参数offset 为根据参数whence 来移动读写位置的位移数。参数 whence 为下列其中一种:
SEEK_SET 从距文件开头offset 位移量为新的读写位置.
SEEK_CUR 以目前的读写位置往后增加offset 个位移量.
SEEK_END 将读写位置指向文件尾后再增加offset 个位移量.
当whence 值为SEEK_CUR 或SEEK_END 时, 参数offset 允许负值的出现.
下列是较特别的使用方式:
1) 欲将读写位置移动到文件开头时:fseek(FILE *stream, 0, SEEK_SET);
2) 欲将读写位置移动到文件尾时:fseek(FILE *stream, 0, 0SEEK_END);
返回值:当调用成功时则返回0, 若有错误则返回-1, errno 会存放错误代码.
附加说明:fseek()不像lseek()会返回读写位置, 因此必须使用ftell()来取得目前读写的位置.
fseek(fp,20,SEEK_SET);
//意思是把fp文件读写位置指针从文件开始后移20个字节.
ftell函数是用来获取文件的当前读写位置;
函数原型: long ftell(FILE *fp)
函数功能:得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.
ban=ftell(fp);
//是获取fp指定的文件的当前读写位置,并将其值传给变量ban.
fseek函数与ftell函数综合应用:
分析:可以用fseek函数把位置指针移到文件尾,再用ftell函数获得这时位置指针距文件头的字节数,这个字节数就是文件的长度.
- #include <stdio.h>
- main()
- {
- FILE *fp;
- char filename[80];
- long length;
- printf("Input the file name:");
- gets(filename);
- fp=fopen(filename,"rb");
- if(fp==NULL)
- printf("file not found!/n");
- else
- {
- fseek(fp,OL,SEEK_END);
- length=ftell(fp);
- printf("the file length %1d bytes/n",length);
- fclose(fp);
- }
- }