Writing to a file using ofstream

C++ provides classes to input or output characters to or from files. To write to a file, we use ofstream.

Two modes are used in writing to a file. ios::trunc and ios::app. ios::trunc removes everything from a file and writes from scratch. ios::app adds data to the file from the new line.

Write a program to output to a file using ofstream. If no mode is provided, ios::trunc is used.

#include<iostream>
#include<fstream>
using namespace std;
int main(){
	ofstream out;
	out.open("myfile.txt");
	if(!out){
		cout<<"Error in opening"<<endl;
		return 1;
	}
	out<<"My "<<123<<endl;
	out<<"Code "<<124<<endl;
	out<<"Partner "<<125<<endl;
	out.close();
	return 0;
}

We get a file named myfile.txt

output of the above program. ofstream, ios::trunc
output of the above program. ofstream, ios::trunc

Now, we use ios::app for the same file. The following code will append data to the same file.

#include<iostream>
#include<fstream>
using namespace std;
int main(){
	ofstream out;
	out.open("myfile.txt",ios::app);
	if(!out){
		cout<<"Error in opening"<<endl;
		return 1;
	}
	out<<"My "<<23<<endl;
	out<<"Code "<<24<<endl;
	out<<"Partner "<<25<<endl;
	out.close();
	return 0;
}
output of the above program. ofstream, ios::app
output of the above program. ofstream, ios::app

2 Replies to “Writing to a file using ofstream”

Leave a Reply

Your email address will not be published. Required fields are marked *