#include#include int main () { std::ofstream myfile; myfile.open ("example.txt"); //opens file named example.txt if (myfile.is_open()) //checking if file is open { myfile << "Writing this to a file.\n"; //writing data to file myfile.close(); //closing file } else std::cout << "Unable to open file"; //if file couldn't be opened return 0; }
#includeThis example opens the file named "example.txt" for appending to it using the `ios_base::app` flag passed to `open`. It then checks if the file is open and appends a line of text to the end of the file using the output stream operator `<<` and closes the file with the `close` method. If the file could not be opened, it returns an error message. Both examples use the `fstream` package library to access files for reading and writing.#include int main () { std::ofstream myfile; myfile.open ("example.txt", std::ios_base::app); //opens file named example.txt and appends to it if (myfile.is_open()) //checking if file is open { myfile << "Appending this data to the end of the file.\n"; //appending data to file myfile.close(); //closing file } else std::cout << "Unable to open file"; //if file couldn't be opened return 0; }