首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C/C++ 取得檔案大小的四種常用方法

     編輯:關於C++

在 C/C++ 中獲取檔案大小有多種 API 可用,本文比較四種常見方法:_stat、filelength、MFC CFile::GetLength、Win32 API GetFileSize,並給出完整可編譯範例程式。

方法比較

方法適用平台備註
_stat()跨平台 (POSIX/Windows)需 <sys/stat.h>,回傳結構含 st_size
filelength(fileno(fp))Windows (CRT)需先 fopen,再取檔案代碼
CFile::GetLength()MFC 專案物件導向封裝,需 afx.h
GetFileSize()Win32 API需 CreateFile 取得 Handle,支援大檔案 (配合 GetFileSizeEx)

完整範例程式


#include 
#include 
#include 
#include 
#define _AFXDLL
using namespace std;

void main() {
    char* filepath = "..\\test.ncb";

    // 方法一:_stat
    struct _stat info;
    _stat(filepath, &info);
    cout << info.st_size << endl;

    // 方法二:filelength
    FILE* file = fopen(filepath, "rb");
    if (file) {
        cout << filelength(fileno(file)) << endl;
        fclose(file);
    }

    // 方法三:CFile
    CFile cfile;
    if (cfile.Open(filepath, CFile::modeRead))
        cout << cfile.GetLength() << endl;

    // 方法四:Win32 API
    HANDLE h = CreateFile(filepath, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    if (h != INVALID_HANDLE_VALUE) {
        cout << GetFileSize(h, NULL) << endl;
        CloseHandle(h);
    }
}

大檔案支援

32 位元 GetFileSize 限制 4GB,大檔案請改用 GetFileSizeEx(需 Vista+)或 GetFileSize 搭配 lpFileSizeHigh 參數。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved