将文本文件的内容附加到C ++中的另一个文件 [英] Appending content of text file to another file in C++
问题描述
如何打开一个文本文件并将其所有行附加到C ++中的另一个文本文件中?我发现大多数解决方案是将文件从字符串分别读取,然后从字符串写入文件。可以优雅地结合吗?
How can you open a text file and append all its lines to another text file in C++? I find mostly solutions for separate reading from a file to a string, and writing from a string to a file. Can this elegantly be combined?
并不总是认为两个文件都存在。访问每个文件时都应该返回布尔值。
It is not always given that both files exist. There should be a bool return when accessing each of the files.
很抱歉,如果这已经不合时宜:是否将文本内容附加到文件中而不会发生冲突?意思是多个程序可以同时执行此操作(行的顺序无关紧要)?如果不是,那是什么(原子的)替代方法?
I'm sorry if this is already off-topic: Is appending text content to a file conflict-free in the meaning that multiple programs can do this simultaneously (the order of the lines DOESN'T matter) ? If not, what would be an (atomic) alternative?
推荐答案
我只能说打开文件并将其附加到另一个文件中。文件:
I can only speak for opening a file and appending it to another file:
std::ifstream ifile("first_file.txt");
std::ofstream ofile("second_file.txt", std::ios::app);
//check to see that the input file exists:
if (!ifile.is_open()) {
//file not open (i.e. not found, access denied, etc). Print an error message or do something else...
}
//check to see that the output file exists:
else if (!ofile.is_open()) {
//file not open (i.e. not created, access denied, etc). 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
这篇关于将文本文件的内容附加到C ++中的另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!