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函數獲得這時位置指針距文件頭的字節數,這個字節數就是文件的長度.
原文:http://blog.csdn.net/swliao/archive/2009/09/04/4518012.aspx
- #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);
- }
- }