1

I need to be able to create a non-existent file. The design is as follows : I have 1 thread for all file IO, and in the data structure that encapsulates the file, I have a std::fstream file_handle.

Can I create and open this file in the mode - std::fstream::in | std::fstream::out | std::fstream::app ? I need this because I have to use this one handle to do both - reads, and writes to the end of the file.

However this is not creating the file. Here's what I have :

class file_io
{
   std::string filename;
   std::fstream file_handle;
   file_io(std::string name)
   {
      filename = name;
   }
   void open_file()
   {
      if(!file_handle.is_open())
      {
          file_handle.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::app);
          if(!file_handle.is_open())
          {
              std::cout << "Could not open file " << filename ;
          }
          else
          {
              std::cout << "successfully opened file " << filename;
          }
      }
   }
   ~file_io()
   {
      if(file_handle.is_open)
      file_handle.close();
   }
};

I call onto open_file each time I need to write into end of the file, or read the file contents. But the file does not get created. Can anyone please help me understand what I am doing wrong here, and what the right approach is to solve my problem?

Also, if the only alternative is to have to different file handles, one for append(need to create here as well) and one for reads, is it okay if I read the file while the file handle for append is still open? Also, what should the mode of opening be for create if non-existent and append ?

timrau
  • 22,578
  • 4
  • 51
  • 64
Roshan
  • 21
  • 1
  • 3
  • http://stackoverflow.com/questions/748014/do-i-need-to-manually-close-a-ifstream – Brandon Mar 12 '14 at 01:09
  • FWIW: I'd like to point out that you don't specify public: or private:. In a class, everything will default to private. You shouldn't even be able to compile code that calls your open function. – HotPlasma May 11 '17 at 15:01

2 Answers2

1

So reading the docs on std::stream open method it looks like the open will fail when both 'in' and 'app' are specified in the open. Try leaving the 'in' off and see what happens.

"If the mode has both trunc and app set, the opening operation fails. It also fails if either is set but out is not, or if both app and in are set."

std::fstream reference

DannyK
  • 1,342
  • 16
  • 23
0

As per the C++ 98 documentation (I presume you are using C++98), you cannot open a file with both modes in and app.

As for having multiple handles on a file, this should help: Reading and writing to the same file using the same fstream.

Community
  • 1
  • 1
Alex
  • 699
  • 1
  • 10
  • 20