Learn how to create files and write data to them using ofstream.
To write data to a file in C++, you use the `ofstream` class from the `<fstream>` library. The process involves three main steps. First, you create an `ofstream` object and open a file. You can do this in one step: `std::ofstream myFile("example.txt");`. This creates an `ofstream` object named `myFile` and attempts to open (or create, if it doesn't exist) a file named `example.txt` for writing. By default, opening a file in this way overwrites its existing content. To append to the end of the file instead, you can specify a second argument: `std::ofstream myFile("example.txt", std::ios::app);`. Second, after opening the file, it's good practice to check if the file was opened successfully. You can do this by treating the file stream object as a boolean: `if (myFile.is_open()) { ... }`. Third, you write data to the file using the stream insertion operator (`<<`), just as you would with `std::cout`. For example, `myFile << "Hello, File!\n"; myFile << 42;`. Finally, and most importantly, you must close the file when you are done writing. This is done by calling the `.close()` method: `myFile.close();`. Closing the file ensures that all the data you've written is flushed from the buffer and saved to the disk. A more modern and safer approach is to use the RAII idiom; when the `ofstream` object goes out of scope, its destructor is automatically called, which closes the file for you. This avoids leaving files open accidentally.