2013-10-29 120 views
2

如何打開一個文本文件並將其所有行追加到C++中的另一個文本文件中?我發現大多數解決方案用於從文件單獨讀取字符串,並從字符串寫入文件。這可以優雅地結合起來嗎?將文本文件的內容追加到C++中的另一個文件中

並不總是給出這兩個文件存在。訪問每個文件時應該有一個返回值。

對不起,如果這已經是焦點話題:是否將文本內容追加到無衝突文件中,意思是多個程序可以同時執行此操作(線的順序無關緊要)?如果不是,那麼(原子)選擇是什麼?

+0

可能重複[追加一個新行一個文件(日誌文件)在C++](http://stackoverflow.com/questions/10071137/appending-a-new-line-in-a-filelog-file-in-c) – KevinDTimm

+0

@Kevin :這個問題似乎沒有解決多個同時編寫的問題。 –

+0

從我測試的沒有衝突。我將此線程標記爲已回答。 – fotinsky

回答

6

我只能打開一個文件,並將其附加到另一個文件說:

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

+0

請不要忘記最終關閉流。 – crisron

1
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; 
} 
相關問題