在C語言中測試文件的大小,主要使用二個標准函數。
1.fseek
函數原型:int fseek ( FILE * stream, long int offset, int origin );
參數說明:stream,文件流指針;offest,偏移量;orgin,原(始位置。其中orgin的可選值有SEEK_SET(文件開始)、SEEK_CUR(文件指針當前位置)、SEEK_END(文件結尾)。
函數說明:對於二進制模式打開的流,新的流位置是origin + offset。
2.ftell
函數原型:long int ftell ( FILE * stream );
函數說明:返回流的位置。對於二進制流返回值為距離文件開始位置的字節數。
獲取文件大小C程序(file.cpp):
1 #include <stdio.h> 2 3 int main () 4 { 5 FILE * pFile; 6 long size; 7 8 pFile = fopen ("file.cpp","rb"); 9 if (pFile==NULL) 10 perror ("Error opening file"); 11 else 12 { 13 fseek (pFile, 0, SEEK_END); ///將文件指針移動文件結尾 14 size=ftell (pFile); ///求出當前文件指針距離文件開始的字節數 15 fclose (pFile); 16 printf ("Size of file.cpp: %ld bytes.\n",size); 17 } 18 return 0; 19 }