herzl shemuelian
herzl shemuelian

Reputation: 3498

std::fstream doesn't create file

I am trying to use std::fstream for io to file, and I want to create the file if it doesn't already exist.

  std::fstream my_stream
  my_stream.open("my_file_name",std::fstream::binary | std::fstream::in | std::fstream::out);
  if(!my_stream)
      std::cout<<"error"<<strerror(errorno);

I get this result: "No such file or directory."

How can I create the file in this case?

Upvotes: 40

Views: 26728

Answers (3)

Ben
Ben

Reputation: 151

You can check the reference from std::basic_filebuf::open

If you use out|in which is the default mode, it is equivalent to using r+ as access mode in fopen, so it cannot create a new file.

So if you want to create a fstream that can read and write a new file, you can use in|out|trunc as w+

And you can create or write to end if file exists by using in|app or in|out|app as a+

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

You're specifying std::fstream::in in your call to fstream::open(). This is known to force it to require an existing file.

Either remove std::fstream::in from your mode argument, or specify std::fstream::trunc in addition to the other flags.

Upvotes: 55

Nick
Nick

Reputation: 2803

It's a little messy but works. Doesn't overwrite the file if it exists but creates a new one if the first open fails.

std::fstream my_stream
my_stream.open("my_file_name",std::fstream::binary | std::fstream::in | std::fstream::out);

if(!my_stream)
{
    my_stream.open("my_file_name",std::fstream::binary | std::fstream::trunc | std::fstream::out);    
    my_stream.close();
    // re-open with original flags
    my_stream.open("my_file_name",std::fstream::binary | std::fstream::in | std::fstream::out);
}
else
{
    // read something
} 

// read/write here

Upvotes: 16

Related Questions