I want to read data from a file, store it into an array, and then display it on the screen.
After doing that, I need to write a line to the end of the file that I have read the data from.
I did the first part. But I couldn't complete the second one. I used different modes when opening the file, but the problem is that the data in the file is being erased after writing to the file.
Can you please help me!
When you read through the entire file, to the end, there is an error bit set to indicate the end of file. While that bit is set, no further operations can be done until the bit is cleared. Here is a sample program for opening a file, reading from it, and then finally appending a line. I hope that helps.
using namespace std;
fstream fs("test.txt", ios::in | ios::out);
// check if file was found
// if not found, create it.
fs.open("test.txt", ios::in | ios::out | ios::trunc);
// check for successful opening of file.
// get all lines in the file
while( ! fs.eof())
cout << s << endl;
// clear the end-of-file error bit
// append a line to the file
fs << "abc" << endl;
// file would close automatically when the
// fs destructor executes, but we can close it here manually
cout << "Cannot open or create the file\n";