查了一下發現同C語言的文件操作函數便可以很容易的實現這樣的功能。在自己實現的函數中使用到的函數就只有fseek和ftell。它們的說明如下:
fseek
語法:
#include <stdio.h> int fseek( FILE *stream, long offset, int origin );
函數fseek()為給出的流設置位置數據. origin的值應該是下列值其中之一(在stdio.h中定義):
名稱 說明
SEEK_SET 從文件的開始處開始搜索
SEEK_CUR 從當前位置開始搜索
SEEK_END 從文件的結束處開始搜索
fseek()成功時返回0,失敗時返回非零. 你可以使用fseek()移動超過一個文件,但是不能在開始處之前. 使用fseek()清除關聯到流的EOF標記.
ftell
語法:
#include <stdio.h> long ftell( FILE *stream );
代碼如下:ftell()函數返回stream(流)當前的文件位置,如果發生錯誤返回-1.
#include <sys/stat.h> #include <unistd.h> #include <stdio.h> /* 函數名:getFileSize(char * strFileName) 功能:獲取指定文件的大小 參數: strFileName (char *):文件名 返回值: size (int):文件大小 */int getFileSize(char * strFileName){ FILE * fp = fopen(strFileName, "r"); fseek(fp, 0L, SEEK_END); int size = ftell(fp); fclose(fp); return size;}/* 函數名:getFileSizeSystemCall(char * strFileName) 功能:獲取指定文件的大小 參數: strFileName (char *):文件名 返回值: size (int):文件大小 */int getFileSizeSystemCall(char * strFileName){ struct stat temp; stat(strFileName, &temp); return temp.st_size;}int main(){ printf("size = %d/n", getFileSize("getFileSize.cpp")); printf("size = %d/n", getFileSizeSystemCall("getFileSize.cpp")); return 0;}
新聞熱點
疑難解答
圖片精選