如何防止使用ofstream覆盖文本文件中的信息?

时间:2014-12-23 23:57:14

标签: c++

我目前正在学习C ++而我正在尝试将文本添加到文件中,但是它会一直覆盖它,无论如何我可以添加内容吗?

#include <iostream>
#include <cstdlib>
#include <fstream>
int main()
{
    std::ofstream fil3;
    fil3.open("test.txt");
    file3 << " bye!"; // replaces text already existing in file :(
    fil3.close();
    return 0;

}

所以,我已经有了一个文字文件,其中包含&#34; Good&#34;在其中,我想尝试添加&#34; bye!&#34;它,所以我有&#34;再见!&#34;。有人可以向我解释一下我应该在这里使用什么功能?谢谢!

1 个答案:

答案 0 :(得分:4)

打开文件时,请使用追加标记:

file3.open("test.txt", std::ofstream::app);

您可以阅读有关文件操作选项here的更多信息。

相关问题