Create Files with C++ ofstream
In C++, using ofstream allows you to create a new file and open it to write data into it. Here is a simple example code that demonstrates how to use ofstream to create a file named example.txt and write data into it:
#include <iostream>
#include <fstream>
int main() {
// 创建一个名为example.txt的文件并打开它
std::ofstream outfile("example.txt");
// 检查文件是否成功打开
if(outfile.is_open()){
std::cout << "文件成功创建并打开" << std::endl;
// 向文件中写入数据
outfile << "Hello, world!" << std::endl;
// 关闭文件
outfile.close();
} else {
std::cout << "文件创建失败" << std::endl;
}
return 0;
}
In the code above, the
After compiling and running the code above, a file named example.txt will be created in the current directory, with the line “Hello, world!” written to it.