问题
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