方法
- 逐行讀取檔案內容至
std::vector<std::string>。
- 寫回時略過最後一個元素(
end()-1)。
程式碼示範
/* main.cpp
* Created on: 2014.06.08
* Author: Spike
*/
#include <windows.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main() {
vector<string> tmp_files;
ifstream infile("w.txt");
if (!infile) { cout << "fail!" << endl; return 0; }
string lineContent;
while (getline(infile, lineContent, '\n')) {
tmp_files.push_back(lineContent + "\n");
}
infile.close();
ofstream outfile("w2.txt", ios::out);
copy(tmp_files.begin(), tmp_files.end() - 1,
ostream_iterator<string>(outfile));
cout << "ok!" << endl;
outfile.close();
return 0;
}
範例
原始檔 (w.txt):
Female
Sister
Girl
Woman
Old Woman
輸出檔 (w2.txt):
Female
Sister
Girl
Woman
替代方案
- 若檔案極大,可雙向迭代器從尾端讀取尋找最後一個換行符,截斷檔案(
std::fstream::truncate),避免全量載入記憶體。
- 使用
std::filesystem::copy_file 配合流處理管線(C++17)。