std :: fstream不创建文件

我正在尝试将std :: fstream用于io来归档,并且如果文件尚不存在,我想创建该文件。

  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);

我得到这个结果:          “无此文件或目录。”

在这种情况下如何创建文件?

最佳答案

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.