Adrian Maire
Adrian Maire

Reputation: 14875

How to use a single fstream for creation, reading and writing a file

I would like to access a file through fstream with the following requirements:

ios_base::in seems to disable file creation
ios_base::out seems to disable file reading

Is this possible? How?

#include <iostream>
#include <sstream>
#include <fstream>
#include <cassert>

using namespace std;

int main()
{
   auto mode = ios_base::in|ios_base::out;
   std::string filePath = "./test.txt";
   std::string content1 = "Any content 1";
   std::string content2 = "Any content 2";

   {
        std::remove(filePath.c_str());
   }

   {// Test creation
       // make sure test.txt is missing / does not exists
       fstream file(filePath, mode);
       assert(file.is_open() && file.good());
       file << content1;
   }

   { // Test reading & writing
       fstream file(filePath, mode);

       // read
       file.seekg(0);
       std::stringstream buffer1;
       buffer1 << file.rdbuf();
       cout << buffer1.str() << endl;
       assert(buffer1.str()==content1);

       // write
       file.seekp(0);
       file << content2;
       assert(file.is_open() && file.good());

       // read
       file.seekg(0);
       std::stringstream buffer2;
       buffer2 << file.rdbuf();
       cout << buffer2.str() << endl;
       assert(buffer2.str()==content2);
   }

    return 0;
}

Run it

Upvotes: 0

Views: 85

Answers (1)

returnVoid
returnVoid

Reputation: 87

Only with fstream I'd say no.

You might want to have something similar with the trunc mode but you'll lose everything if the file exists (which might be a problem, if not go for trunc + out)

The other way is to check if the file exists, if not you create it (whichever way). Then you open with In and Out and do your stuff.

It kind of doesn't make sense to be able to read inside an empty file you just created from the cpp point of view

Upvotes: 1

Related Questions