C++ 写入txt文件内容并追加内容

咨询通义千问的“C++ 写入txt文件内容并追加内容”:

可以使用ofstream类来写入txt文件内容。若想追加内容,可以使用ios::app标志来创建输出流对象,然后在写入时将其设置为ios::app。以下是一个示例代码:

#include 
#include 
using namespace std;

int main() {
    ofstream out("example.txt", ios::app);
    out << "Hello, World!" << endl;
    out << "This is an example." << endl;
    out.close();
    return 0;
}

在这个例子中,我们创建了一个名为“example.txt”的输出流对象,并将其设置为ios::app。然后,我们写入了两行文本,并在文件末尾添加了它们。最后,我们关闭了输出流对象。

若想在文件开头追加内容,可以使用ios::ate标志来创建输出流对象。这将导致输出流对象自动跳过文件开头的内容,并将下一个写入操作添加到文件末尾。以下是一个示例代码:

#include 
#include 
using namespace std;

int main() {
    ofstream out("example.txt", ios::ate | ios::out);
    out << "This is an example." << endl;
    out << "Hello, World!" << endl;
    out.close();
    return 0;
}

在这个例子中,我们创建了一个名为“example.txt”的输出流对象,并将其设置为ios::ate | ios::out。然后,我们写入了两行文本,并在文件末尾添加了它们。最后,我们关闭了输出流对象。

 

你可能感兴趣的:(C++,c++)