2013-10-29 210 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; 
} 
相关问题