c++创建文件并写入文件
时间: 2023-06-23 07:55:09 浏览: 70
在C++中,创建并写入文件可以使用ofstream类和fstream类。下面提供两种方法:
1. 使用ofstream类
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile("example.txt"); // 创建并打开文件
if (outfile.is_open()) { // 判断文件是否打开成功
outfile << "This is a line." << endl; // 写入数据
outfile.close(); // 关闭文件
cout << "Write to file successfully!" << endl;
} else {
cout << "Failed to open file." << endl;
}
return 0;
}
```
在这个例子中,我们使用ofstream类创建并打开了名为example.txt的文件。如果文件打开成功,我们就可以使用“<<”运算符将数据写入文件。最后,我们使用close()函数关闭文件。
2. 使用fstream类
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file("example.txt", ios::out); // 创建并打开文件
if (file.is_open()) { // 判断文件是否打开成功
file << "This is a line." << endl; // 写入数据
file.close(); // 关闭文件
cout << "Write to file successfully!" << endl;
} else {
cout << "Failed to open file." << endl;
}
return 0;
}
```
在这个例子中,我们使用fstream类创建并打开了名为example.txt的文件。第二个参数ios::out表示以写入模式打开文件。如果文件打开成功,我们就可以使用“<<”运算符将数据写入文件。最后,我们使用close()函数关闭文件。
无论是使用ofstream类还是fstream类,都需要注意文件打开是否成功。如果文件打开失败,我们就不能写入数据。