c语言fseek函数的总结

来源:互联网 发布:团队优化的原则包括 编辑:程序博客网 时间:2024/06/06 03:45

头文件:#include <stdio.h>

函数原型:int fseek(FILE *stream, long offset, int fromwhere);

参数:

    stream:指向打开的文件指针。

    offset:以基准点为起始点的偏移量。

    fromwhere:基准点。

返回值:

    成功,返回0;失败返回-1。

其中基准点包括这三个枚举:

    SEEK_SET:文件头。

    SEEK_CUR:当前位置。

    SEEK_END:文件件尾。

作用:重定位流(数据流/文件)的内部位置指针。


描述:函数设置文件指针stream的位置。如果执行成功,stream将指向以fromwhere为基准,偏移offset个字节的位置。如果执行失败,则不改变stream指向的位置。

程序实例:

#include <stdio.h>long filesize(FILE*stream);int main(void){    FILE *stream;    stream=fopen("MYFILE.TXT","w+");    fprintf(stream,"Thisisatest");    printf("FilesizeofMYFILE.TXTis%ldbytes\n",filesize(stream));    fclose(stream);    return 0;}long filesize(FILE*stream){    long curpos,length;    curpos=ftell(stream);    fseek(stream,0L,SEEK_END);    length=ftell(stream);    fseek(stream,curpos,SEEK_SET);    return length;}


其他用法:

fseek(fp, 100L, 0);把stream指针移动到离文件开头100字节处;

fseek(fp, 100L, 1);把stream指针移动到离文件当前位置字节处;

fseek(fp, -100L, 2);把stream指针移动到离文件尾100字节处;

上面函数的0, 1, 2分别为SEEK_SET,SEEK_CUR,SEEK_END。