std::fstream doesn't create file

萝らか妹 提交于 2019-12-17 03:41:12

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/8835888/stdfstream-doesnt-create-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!