1. Writing to a file #
Created Saturday 25 April 2020
- Writing to a file - unlike cin and cout, we have to create the objects similar to cin and cout.
- For writing, we need only the out file stream(ofstream) object.
#include<fstream>
int main()
{
// provide the modes app, trunc - by default trunc is assumed
// create an object to handle the file
ofstream outfile("my.txt", ios::app); // it'll create a file(if it doesn't exist), else it will open the file
// or outfile.write("my.txt", ios:app);
outfile << "Hello" << endl;
outfile << 25 << endl;
//closing the file - very important
outfile.close(); // it's free now - i.e the OS knows that we have freed the file for other programs
}