Note 11.9.1.
Try running this program in a real development environment so you can see that the code creates a new file!
std::ofstream object and then use its .open() method to open a file. (ostream is in the fstream library, so you must have that included.) Once that is done, we can write to the file using <<.
data.txt, it closes the file to make sure that it is available to open for reading, and then opens it with an ifstream to read the data back in:
ios::app says to append new output to the end of the file instead of truncating the file:
myOutFile.open("data.txt", ios::app); // add to existing data in the file
output.txt after running the code below?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile("output.txt");
if (!outfile) {
cout << "Unable to open file" << endl;
}
cout << "Powers of 2: ";
outfile << "2 4 8 16 32 64" << endl;
}