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

C語言獲取大文件長度:跨平台 64 位解決方案

     編輯:關於C語言

C語言獲取大文件長度:跨平台 64 位解決方案

傳統 ftell 返回 long 型別,在 32 位系統上限制為 2GB,無法應對現代大文件(如 10GB+ 遊戲安裝包)。本文遞進式介紹從 32 位舊寫法到跨平台 64 位解決方案的完整演進過程。

一、傳統 32 位寫法(受限於 2GB)

long file_getsize(const char *path) {
    FILE *fp = fopen(path, "rb");
    if (!fp) return 0;
    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    fclose(fp);
    return size;
}

缺陷:long 32 位為 4 位元組,最大值 2,147,483,647 (≈2GB)。大文件會溢出返回負值或錯誤值。

二、Windows 平台 64 位方案

使用 _stat64 結構體,st_size 為 64 位整數:

#include <sys/types.h>
#include <sys/stat.h>
#include <inttypes.h>  // PRId64

int64_t file_getsize(const char *path) {
    struct _stat64 info = {0};
    if (!path || !*path) return 0;
    if (_stat64(path, &info) != 0) return 0;
    return info.st_size;
}

測試 4.3GB 文件正確返回 4638924800。

三、Linux 平台 64 位方案

Linux stat 在 64 位系統自動為 stat64,st_size 為 off_t (通常 8 位元組):

#include <sys/stat.h>
#include <inttypes.h>

int64_t file_getsize(const char *path) {
    struct stat info = {0};
    if (!path || !*path) return 0;
    if (stat(path, &info) != 0) return 0;
    return info.st_size;
}

編譯:gcc -Wall -ggdb2 -o main_linux.out main_linux.c

四、跨平台統一介面

利用編譯器預定義巨集區分平台:

#if defined(_MSC_VER) || defined(_WIN32)
    #define STAT_STRUCT _stat64
    #define STAT_FUNC _stat64
#else
    #define STAT_STRUCT stat
    #define STAT_FUNC stat
#endif

int64_t file_getsize(const char *path) {
    STAT_STRUCT info = {0};
    if (!path || !*path) return 0;
    if (STAT_FUNC(path, &info) != 0) return 0;
    return info.st_size;
}

五、關鍵型別對照表

平台結構體大小欄位型別位數
Windows 32/64_stat64st_size__int64 / long long64
Linux 64 位stat (==stat64)st_sizeoff_t (long)64
Linux 32 位stat64st_sizeoff64_t64
POSIX 標準statst_sizeoff_t實現定義

六、效能對比

  • fseek/ftell:需移動檔案指標,系統調用開銷大
  • stat 族:直接讀取 inode 元數據,無需開啟文件,**效能高階數量級**

七、完整測試程式框架

#include <stdio.h>
#include <inttypes.h>

int64_t file_getsize(const char *path);

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        printf("%s => %" PRId64 "\n", argv[i], file_getsize(argv[i]));
    }
    return 0;
}

八、總結建議

  1. 棄用 ftell:無法支援 >2GB 文件
  2. 優先 stat 族:高效、無需開啟文件、原生 64 位
  3. 使用 int64_t/PRId64:跨平台型別與格式化
  4. 平台巨集隔離:_MSC_VER、_WIN32 區分 Windows
  5. 錯誤處理:檢查路徑有效性、系統調用返回值

「C 語言細節繁多,但對於極致效能與資源控制,無可替代。選擇適合的工具,而非尋找完美的語言。」

夢想與現實

有夢想的人令人羨慕,也令人惋惜。愛所愛,開心就好。

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