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

C++ 讀取大型數據檔案運算並輸出高效方案

     編輯:程式設計綜合問答

需求

讀取 ~10 萬行、4 欄的 `.dat` 檔,第 1 欄保留,第 2-4 欄乘以常數,寫入新檔。

高效實現:流式處理、避免全載入記憶體

#include 
#include 
#include 
#include 

int main() {
    const double factor2 = 1.5, factor3 = 2.0, factor4 = 0.5; // 例:乘法因子
    std::ifstream in("input.dat");
    std::ofstream out("output.dat");
    
    if (!in || !out) {
        std::cerr << "檔案開啟失敗\n";
        return 1;
    }
    
    std::string col1;
    double c2, c3, c4;
    size_t lineCount = 0;
    
    // 逐行讀取、處理、寫入
    while (in >> col1 >> c2 >> c3 >> c4) {
        out << col1 << ' ' 
            << std::fixed << std::setprecision(6) 
            << c2 * factor2 << ' ' 
            << c3 * factor3 << ' ' 
            << c4 * factor4 << '\n';
        
        if (++lineCount % 10000 == 0) 
            std::cout << "已處理 " << lineCount << " 行\r" << std::flush;
    }
    
    std::cout << "\n完成,共處理 " << lineCount << " 行\n";
    return 0;
}

關鍵優化點

  1. 串流處理:`ifstream` + `ofstream` 逐行讀寫,記憶體佔用 O(1),不受檔案大小限制。
  2. 避免 `std::endl`**:用 `'\n'`,`endl` 會強制 flush 降低效能。
  3. 關閉同步**:`std::ios::sync_with_stdio(false); std::cin.tie(nullptr);` 可顯著提升 C++ I/O 速度(放在 `main` 開頭)。
  4. 格式化輸出**:`std::fixed << std::setprecision(6)` 統一浮點數格式。
  5. 錯誤處理**:檢查檔案開啟、讀取失敗(格式錯誤行)。

進階:大檔案並行處理 (C++17)

若 CPU 核心多、檔案極大 (GB 級),可記憶體映射 (`mmap`) + 多執行緒分塊處理,但 10 萬行**完全不需要**,單執行緒流式處理通常 < 1 秒。

測試資料格式範例

# input.dat
ID001 10.5 20.3 30.1
ID002 15.2 25.8 35.4
...

結論

兩個 `fstream` 物件、一個 `while` 迴圈、逐行讀取運算寫入,是處理此類中型結構化數據檔最簡潔高效的 C++ 方案。

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