合併 `1.txt`、`2.txt`... 為 `output.txt`。檔案為表格格式,**表頭相同**,合併後**僅保留第一檔表頭**,資料行連續輸出。
#include
#include
#include
#include
int main(int argc, char* argv[]) {
if (argc < 4) {
std::cerr << "Usage: merge.exe file1.txt file2.txt ... output.txt\n";
return 1;
}
std::string outPath = argv[argc - 1];
std::ofstream fout(outPath);
if (!fout) { std::cerr << "Cannot open output\n"; return 1; }
bool firstFile = true;
for (int i = 1; i < argc - 1; ++i) {
std::ifstream fin(argv[i]);
if (!fin) { std::cerr << "Cannot open " << argv[i] << "\n"; continue; }
std::string line;
bool firstLine = true;
while (std::getline(fin, line)) {
if (firstLine) {
if (firstFile) {
fout << line << '\n'; // 寫入表頭
}
// 非第一檔:略過表頭
firstLine = false;
} else {
fout << line << '\n'; // 寫入資料行
}
}
firstFile = false;
fin.close();
}
fout.close();
std::cout << "Merged to " << outPath << "\n";
return 0;
}
g++ -std=c++17 merge.cpp -o merge
./merge 1.txt 2.txt 3.txt output.txt
若檔案為標準 CSV (欄位含逗號用雙引號包裹),建議用成熟庫:**`csv2`**, **`fast-cpp-csv-parser`**, **`RapidCSV`** 解析後再寫入,避免手寫解析器 Bug。
合併同表頭文字檔:**第一檔寫表頭,後續檔略過首行,資料行逐行追加寫入**。C++ `fstream` 逐行流式處理,記憶體安全、效能佳、跨平台。