0

Hello. I'm using this constuction to write to file:

#include <iostream>
#include <fstream>
using namespace std;


int main () {
	char data [50];
	cout << "Enter data\n";
	cin >> data;
	ofstream file("data.txt");
	if (!file) {
		cout << "File opening error";
		cin.get();
		return 1;
	}
	file << data;
	file.close();
	cout << "Data writed" << endl;
	return 0;
}

But then program overwrites all file. How can i make it to write data to file's ending?

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by 3bdelhakeem
1

replace this line

ofstream file("data.txt");

with this

ofstream file("data.txt", ios::app);

We changed the second parameter of the constructor which is the open mode, to ios::app, so that when you write to the file the output is appended to the end of the file.

if you want to open the file with two openmodes, then use the OR operator | to separate between modes:

ofstream file("data.txt", ios::in | ios::out);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.