You are here:

C++/Input\Output files

Advertisement


Question
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!

Answer
Hello AHR

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.

Best regards
Zlatko

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
   fstream fs("test.txt", ios::in | ios::out);
   // check if file was found
   if (!fs.good())
   {
       // if not found, create it.
       fs.open("test.txt", ios::in | ios::out | ios::trunc);
   }

   // check for successful opening of file.
   if (fs.good())
   {

       string s;
       // get all lines in the file
       while( ! fs.eof())
       {
         getline(fs, s);
         cout << s << endl;
       }

       // clear the end-of-file error bit
       fs.clear();

       // 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
       fs.close();
   }
   else
   {
       cout << "Cannot open or create the file\n";
   }
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2016 About.com. All rights reserved.