[C、C++] 計算檔案大小程式

在C 或C++語言中,
常常會有需要開啟檔案、讀檔、寫檔等動作,
但如果需要計算開啟的檔案檔案容量大小時,
該如何辦到呢?

在這邊提供一個範例給大家

這支程式主要的流程是
1. 開啟一個檔案
2. 將檔案的指標移到檔案的最後
3. 取得目前指標的位置,目前的位置,也就是檔案的大小,單位為Byte
4. 將指標移回檔案的開頭

#include <iostream>using namespace std; long doGetFileSize(const char* filePath, const char* mode){ long fileLength = 0; FILE *fp; //開啟檔案 if(! (fp = fopen(filePath, mode))){ //File Open Error return -1; } //移動指標到檔案的結尾 if(fseek(fp, 0, SEEK_END)) { //File seek error. return -1; } //取得檔案大小 單位byte fileLength = ftell(fp); //移動指標回檔案起始 rewind(fp)return fileLength;}

 

Related posts:

  1. 何謂callback function?
This entry was posted in 程式語言. Bookmark the permalink.

One Response to [C、C++] 計算檔案大小程式

發表迴響

您的電子郵件位址並不會被公開。 必要欄位標記為 *

*

您可以使用這些 HTML 標籤與屬性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>