#include// includes the CFile class int main() { std::ofstream myfile; // creates an instance of CFile called "myfile" myfile.open("example.txt"); // opens the file "example.txt" myfile << "Writing to the file.\n"; // writes to the file myfile.close(); // closes the file return 0; }
#includeThis code opens the file "example.txt", reads each line of the file, outputs each line to the console, and then closes the file. The package library used for this example is also the C++ Standard Library.int main() { std::ifstream myfile("example.txt"); // creates and opens an instance of CFile called "myfile" if (myfile.is_open()) // checks if the file is open { std::string line; while (getline(myfile, line)) // reads each line of the file { std::cout << line << '\n'; // outputs each line to the console } myfile.close(); // closes the file } else std::cout << "Unable to open file"; // outputs this if the file cannot be opened return 0; }