首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Linux fstat 讀取 3GB 大檔報錯:需定義 _FILE_OFFSET_BITS=64

     編輯:程式設計疑難解答

32 位元程式使用 fstat 讀取 >2GB 檔案時,struct stat 的 st_size 為 32 位 long,無法容納大檔大小,報錯 Value too large for defined data type (EOVERFLOW)。

解決方法

  1. 編譯時定義大檔支援宏 (在所有原始檔最前面或編譯參數):
    #define _FILE_OFFSET_BITS 64
    #define _LARGEFILE_SOURCE
    #define _LARGEFILE64_SOURCE
    #include <sys/stat.h>
    // 之後 off_t、struct stat 皆為 64 位
  2. 或直接使用 64 位專用 API:
    struct stat64 st;
    fstat64(fd, &st); // st.st_size 為 64 位
    printf("Size: %lld\n", (long long)st.st_size);
  3. 建議:直接編譯 64 位元執行檔:gcc -m64 ...,現代 Linux 發行版預設 64 位,問題自動消失。

驗證

// 測試程式
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    int fd = open("bigfile", O_RDONLY);
    struct stat st;
    fstat(fd, &st);
    printf("Size: %lld bytes\n", (long long)st.st_size);
    close(fd);
    return 0;
}

編譯執行後應正確顯示 3GB+ 大小。

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