将文本文件的内容附加到 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?
并不总是给出两个文件都存在的情况.访问每个文件时应该有一个 bool 返回.
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屋!