讀取 ~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;
}
若 CPU 核心多、檔案極大 (GB 級),可記憶體映射 (`mmap`) + 多執行緒分塊處理,但 10 萬行**完全不需要**,單執行緒流式處理通常 < 1 秒。
# input.dat
ID001 10.5 20.3 30.1
ID002 15.2 25.8 35.4
...
兩個 `fstream` 物件、一個 `while` 迴圈、逐行讀取運算寫入,是處理此類中型結構化數據檔最簡潔高效的 C++ 方案。