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

How do I prevent overwriting information in a text file with the ofstream?

本文关键字:文件 信息 文本 覆盖 何防止 ofstream      更新时间:2023-10-16

我目前正在学习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;
}

所以,我已经有一个带有"好"字样的文本文件,我想尝试添加"再见!",所以我有"再见!有人可以向我解释我应该在这里使用什么功能吗?谢谢!

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

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

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