【问题标题】:C++/fstream: cannot create a new fileC++/fstream:无法创建新文件
【发布时间】:2016-09-19 07:26:50
【问题描述】:

由于某种原因,以下代码无法创建新文件,即如果文件已经存在,它将覆盖它,否则它什么也不做:

#include <fstream>

int main()
{
    std::fstream fs("test_out.log"); // <-- does not create a new file!
    //std::fstream fs("test_out.log", std::ios_base::in | std::ios_base::out); // <-- does not create a new file!

    fs << "TEST" << std::endl;
}

我做错了什么?

C++ 编译器:clang
系统:OS-X 10.9.5

【问题讨论】:

  • 最后你应该写 fs.close()
  • @Android400:手动关闭没有意义。 fs 对象在离开 main 范围时被销毁后,文件在 fs 被销毁时关闭。
  • 是的,在这个例子中手动关闭没有意义,但在其他用法中它不是没用的。
  • @Android400 在其他情况下,其他代码可以实现其他事情,对吧。但这对我们有什么帮助呢?
  • @Android400 C++ 不是 Java。 fstream 的析构函数关闭对象。

标签: c++ file fstream


【解决方案1】:

如果你想创建一个新的文件来写:

std::ofstream fs("test_out.log");

做好工作。

如果您使用std::ios_base::in,该文件必须存在

【讨论】:

  • 为什么std::fstream fs("test_out.log", std::ios_base::in | std::ios_base::out);创建文件失败?
  • @GilsonPJ:如果您使用std::ios_base::in,该文件必须存在。
  • 谢谢。没有in 它正在创建文件
  • 是不是说如果我想在 (ios_base::in | ios_base::out) 模式下打开一个文件,我最好这样做:{ ofstream fs("test_out.log", ios_base: :应用程序); } 首先,保证文件存在?
猜你喜欢
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 2013-03-18
相关资源
最近更新 更多