std::fstream doesn't create file

herzl shemuelian picture herzl shemuelian · Jan 12, 2012 · Viewed 21k times · Source

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?

Answer

Fr&#233;d&#233;ric Hamidi picture Frédéric Hamidi · Jan 12, 2012

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.