C++ fstream File Creation Guide
In C++, we can use the fstream library to create a file. The specific steps are as follows:
- Header file.
#include <fstream>
- Create an fstream object, which can be an ifstream (for reading files), ofstream (for writing files), or fstream (for both reading and writing).
std::ofstream file("filename.txt");
- Write content to the file. You can use the stream operator “<<" to write content.
file << "Hello, World!";
- Close the file. It is necessary to close the file after writing to or reading from it.
file.close();
The complete sample code is as follows:
#include <fstream>
int main()
{
// 创建一个ofstream对象,用于写入文件
std::ofstream file("filename.txt");
// 写入内容到文件
file << "Hello, World!";
// 关闭文件
file.close();
return 0;
}
This will create a file named “filename.txt” and write “Hello, World!” into it.