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 header file is included first. Next, an ofstream object named outfile is created and the filename example.txt is passed as a parameter. Then the is_open() function is used to check if the file has been successfully opened. If so, data is written to the file and finally the file is closed.

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.

bannerAds