fseek和ftell

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函数获得这时位置指针距文件头的字节数,这个字节数就是文件的长度.

#include <stdio.h>

main()

{

   FILE *fp;

   char filename[80];

   long length;

   printf("输入文件名:");

   gets(filename);

   //以二进制读文件方式打开文件

   fp=fopen(filename,"rb");

   if(fp==NULL)

      printf("file not found!/n");

   else

      {

         //把文件的位置指针移到文件尾

          fseek(fp,OL,SEEK_END);

         //获取文件长度;

          length=ftell(fp);

          printf("该文件的长度为%1d字节/n",length);

          fclose(fp);

      }

}

 

#include   <stdio.h>  

   

  #include   <stdlib.h>  

   

   

   

  void   main()  

   

  {    

    FILE   *fp;    

    long   int   size;     

    char   *   buff;  

   

    if   ((fp=fopen("w.dat","rb"))==NULL)   {  

      printf("cannot   open   file/n");    

      exit(1);    

  }  

     

    fseek(fp,0,SEEK_END);  

    size=ftell(fp);  

    buff=(char   *)   malloc(size);  

    fseek(fp,0,SEEK_SET);  

   

    if   (fread(buff,1,size,fp)!=size)   {      

     printf("read   error!!");    

    }      

    free(buff);      

  }  

你可能感兴趣的:(File,null,FP)