如何打開一個文本文件並將其所有行追加到C++中的另一個文本文件中?我發現大多數解決方案用於從文件單獨讀取字符串,並從字符串寫入文件。這可以優雅地結合起來嗎?將文本文件的內容追加到C++中的另一個文件中
並不總是給出這兩個文件存在。訪問每個文件時應該有一個返回值。
對不起,如果這已經是焦點話題:是否將文本內容追加到無衝突文件中,意思是多個程序可以同時執行此操作(線的順序無關緊要)?如果不是,那麼(原子)選擇是什麼?
如何打開一個文本文件並將其所有行追加到C++中的另一個文本文件中?我發現大多數解決方案用於從文件單獨讀取字符串,並從字符串寫入文件。這可以優雅地結合起來嗎?將文本文件的內容追加到C++中的另一個文件中
並不總是給出這兩個文件存在。訪問每個文件時應該有一個返回值。
對不起,如果這已經是焦點話題:是否將文本內容追加到無衝突文件中,意思是多個程序可以同時執行此操作(線的順序無關緊要)?如果不是,那麼(原子)選擇是什麼?
我只能打開一個文件,並將其附加到另一個文件說:
std::ifstream ifile("first_file.txt", std::ios::in);
std::ofstream ofile("second_file.txt", std::ios::out | std::ios::app);
//check to see that it exists:
if (!ifile.is_open()) {
//file not found (i.e. it is not opened). Print an error message or do something else.
}
else {
ofile << ifile.rdbuf();
//then add more lines to the file if need be...
}
參考:的
http://www.cplusplus.com/doc/tutorial/files/ https://stackoverflow.com/a/10195497/866930
請不要忘記最終關閉流。 – crisron
std::ifstream in("in.txt");
std::ofstream out("out.txt", std::ios_base::out | std::ios_base::app);
for (std::string str; std::getline(in, str);)
{
out << str;
}
可能重複[追加一個新行一個文件(日誌文件)在C++](http://stackoverflow.com/questions/10071137/appending-a-new-line-in-a-filelog-file-in-c) – KevinDTimm
@Kevin :這個問題似乎沒有解決多個同時編寫的問題。 –
從我測試的沒有衝突。我將此線程標記爲已回答。 – fotinsky