c++如何打开文件并继续写入
时间: 2023-08-11 20:20:44 浏览: 330
在 C++ 中,可以使用 ofstream
类来打开文件并写入数据。如果文件已经存在,可以使用 ios::app
标志来将数据添加到文件末尾而不是覆盖原有的数据。
下面是一个简单的示例代码,演示如何打开一个文件并在文件末尾继续写入数据:
#include <iostream>
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("example.txt", std::ios::app);
if (outfile.is_open()) {
outfile << "This is a new line." << std::endl;
outfile.close();
std::cout << "Data has been written to the file." << std::endl;
} else {
std::cout << "Unable to open the file." << std::endl;
}
return 0;
}
在上面的代码中,我们首先创建了一个 ofstream
对象 outfile
,然后调用 open()
函数打开一个名为 "example.txt" 的文件,并使用 ios::app
标志将数据添加到文件末尾。接着,我们检查文件是否成功打开,如果文件成功打开,我们就使用 <<
运算符写入一行新的数据,然后调用 close()
函数关闭文件。最后,我们输出一条消息来表示数据已经成功写入文件。如果文件无法打开,我们会输出一条错误消息。
相关推荐















