将文本文件的内容追加到C++中的另一个文件中

fot*_*sky 2 c++ file atomic append fwrite

如何打开文本文件并将其所有行附加到C++中的另一个文本文件?我主要找到解决方案,用于从文件到字符串的单独读取,以及从字符串写入文件.这可以优雅地结合在一起吗?

并不总是给出两个文件都存在.访问每个文件时应该有一个bool返回.

如果这已经偏离主题,我很抱歉:将文本内容附加到文件中是否存在冲突,这意味着多个程序可以同时执行此操作(行的顺序无关紧要)?如果不是,什么是(原子)替代品?

jrd*_*rd1 6

我只能说打开文件并将其附加到另一个文件:

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...
}
Run Code Online (Sandbox Code Playgroud)

参考文献:

http://www.cplusplus.com/doc/tutorial/files/

/sf/answers/713684821/

  • @crisron 当它们超出范围时会自动关闭 (2认同)