Home > OS >  C Filling, ios::app is working, but not ios::in
C Filling, ios::app is working, but not ios::in

Time:06-04

Here is my code where I try to Append to a file and also read it. Appending is working great however reading is not working. Is it the problem of getline?

#include <fstream>
#include <string>

using namespace std;

int main()
{
   fstream ob1;
   ob1.open("testext", ios::app | ios::in);

   ob1 << "1\n";
   ob1.write("Write\n", 5);

   while (ob1)
   {
       cout << "1" << endl; // Check if compiler goes in while loop
       string a;
       getline(ob1, a);
       cout << a << endl;
   }
   ob1.close();
}

Output

1

CodePudding user response:

you could close the file and reopen it but it would be silly you could use

    //writing code here

    //to push all text to the file and not making errors
    ob1.flush(); 
    // to return reading pointer to the beginning of the file
    ob1.seekg(0,ios_base::beg); 
    
    //reading code here

and side note : use

    string a; 
   while (getline(ob1, a))
   {
       cout << "1" << endl; // Check if compiler goes in while loop
       cout << a << endl;
   }

CodePudding user response:

After writing into the file you are trying to reading its contents. So after performing any one of the operation you need to close the stream and open it again in order to perform different set of operation.

So before while loop add these below 2 lines,

ob1.close( );
ob1.open("testext", ios::app | ios::in);
  • Related