Eduard Kim
Eduard Kim

Reputation: 275

Trying to manipulate files in c++

When using <fstream> library to open and add a stream to an existing file test.rtf and I use the following lines:

char data[100];

// open a file in write mode.
ofstream outfile;
outfile.open("test.rtf");
if (outfile.is_open()) { cout << "file is open" << endl; }

cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.
outfile << data << endl;

And when reading it by using ifstream, the lines input are displayed correctly. The problem is the output file is not modified and lines I have added are not saved. The question might sound very stupid but it's a problem I could not resolve.

Upvotes: 0

Views: 155

Answers (1)

Log_n
Log_n

Reputation: 404

When you << to your file you are just writing to a buffer, not actually "flushing" it to the file itself. If you just close your file you should be fine.

So:

outfile.close()

Also in the future you can flush (actually write from buffer to the file) when you want to write to a file but not close it. .close() flushes then closes for you automatically.

Upvotes: 3

Related Questions