C++ ofstream: File Writing Guide

In C++, ofstream is an output stream class used for writing to files. It is defined in the header file and is used to create an output stream object for writing to files. The ofstream class provides a set of member functions such as open(), close(), write(), and others to facilitate file writing operations.

Here is a simple example of writing to a file using ofstream:

#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("example.txt"); // 创建一个名为example.txt的文件,如果文件不存在则会创建,如果文件已存在则会覆盖

    if (file.is_open()) {
        file << "Hello, World!"; // 将字符串写入文件
        file.close(); // 关闭文件
        std::cout << "File has been written." << std::endl;
    } else {
        std::cout << "Failed to open file." << std::endl;
    }

    return 0;
}

In the example above, a file named example.txt is first created, and the string “Hello, World!” is written to the file. Finally, the file is closed and a message is printed out.

In general, the use of the ofstream class makes file writing operations easy, as it allows for opening, closing, and writing file content using member functions.

bannerAds