如何打开一个文本文件并将其所有行附加到C ++中的另一个文本文件中?我发现大多数解决方案是将文件从文件读到字符串,然后从字符串写到文件。可以优雅地结合吗?
并非总是两个文件都存在。访问每个文件时,应该返回bool。
很抱歉,如果这已经成为题外话:将文本内容附加到文件中是否没有冲突,就意味着多个程序可以同时执行此操作(行的顺序无关紧要)?如果不是,那么(原子)替代方案是什么?
我只能说打开一个文件并将其附加到另一个文件:
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...
}
参考资料:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句