How can I append to a text file?

这一生的挚爱 提交于 2019-12-14 03:54:18

问题


I have a program written in C++ which accepts text from a user and saves it to a text file using file handles. Here are snippets of the program:

The program works fine. The only problem with it is that it does not append the text to the text file. Rather, it "removes" all the existing text and only saves the new text.

That is, the text saved in a previous session of the program is discarded and the new text is saved instead. How can I solve this problem please?


回答1:


Include the O_APPEND flag when opening the file. See the reference page for _open().

As this is C++ consider using an ofstream instead. These are type-safe and remove the requirement of having to specify the length of the arguments being written to the file:

std::ofstream out(full_path, std::ios_base::app);
if (out.is_open())
{
    out << "----Session----\n\n"
        << "Date/Time: " << datetime << "\n\n"
        << "Text: " << text << "\n\n\n\n";
}


来源:https://stackoverflow.com/questions/13200079/how-can-i-append-to-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!