函数fseek、ftell、rewind
int fseek(FILE * _File, long _Offset, int _Origin);
fseek函数是 用来设定文件的当前读写位置.
函数设置文件指针stream的位置。如果执行成功,stream将指向以fromwhere为基准,偏移offset(指针偏移量)个字节的位置,函数返回0。如果执行失败则不改变stream指向的位置,函数返回一个非0值。
超出文件末尾位置,还是返回0。往回偏移超出首位置,还是返回0,小心使用。
第一个参数stream为文件指针。
第二个参数offset为偏移量,正数表示正向偏移,负数表示负向偏移。
第三个参数origin设定从文件的哪里开始偏移,可能取值为:SEEK_CUR、SEEK_END或SEEK_SET。
SEEK_SET:文件开头
SEEK_CUR:当前位置
SEEK_END:文件结尾
函数功能:把fp的文件读写位置指针移到指定的位置.
fseek(fp,20,SEEK_SET); 意思是把fp文件读写位置指针从文件开始后移20个字节.
long len = ftell(fp)
ftell函数是用来获取文件的当前读写位置;ftell函数用于得到文件位置指针当前位置相对与文件首的偏移字节数。在随机方式存取文件时,由于文件位置频繁的前后移动,程序不容易确定文件的当前位置。
函数功能:得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.
ban=ftell(fp); 是获取fp指定的文件的当前读写位置,并将其值传给变量ban.
测试程序
可以用fseek函数把位置指针移到文件尾,再用ftell函数获得这时位置指针距文件头的字节数,这个字节数就是文件的长度.
#include <stdio.h>
int main(int argc, char *argv[])
{
int filesize;
FILE *fp = fopen("demo.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;
}
void rewind(FILE *stream)
C 库函数 void rewind(FILE *stream) 设置文件位置为给定流 stream 的文件的开头。
#include <stdio.h>
int main()
{
char str[] = "This is runoob.com";
FILE *fp;
int ch;
/* 首先让我们在文件中写入一些内容 */
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
fp = fopen( "file.txt" , "r" );
while(1)
{
ch = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", ch);
}
rewind(fp);
printf("\n");
while(1)
{
ch = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", ch);
}
fclose(fp);
return(0);
}