【问题标题】:How to close ofstream after assigning to ostream?分配给ostream后如何关闭ofstream?
【发布时间】:2023-04-04 08:19:02
【问题描述】:

我可以的

std::ostream& out = condition ? std::cout : std::ofstream(filename);

但是如果是out = std::ofstream(filename),我该如何关闭?

【问题讨论】:

  • of.close(),或者让of超出范围。

标签: c++ ofstream ostream


【解决方案1】:

暂时忘记关闭,你的代码:

std::ostream& out = condition ? std::cout : of.open(filename);

开始时不会编译。 std::ofstream::open() 不返回流 - 它返回 void。您可以将其修复为:

std::ostream& out = condition ? std::cout : (of.open(filename), of);

现在回到关闭流,好吧,您不必这样做,因为当流对象超出范围时(即调用析构函数时),析构函数将关闭文件流。所以它会自动为你完成——好吧,在 99.99% 的情况下,除非你正在做一些不寻常的事情,在这种情况下你想明确地关闭它!

【讨论】:

  • @downforme:即使这样也不会编译。请在发布之前尝试编译您的代码。
  • std::ostream& out1 = std::cout; std::ostream& out2 = std::ofstream(""); 编译
  • @downforme: 否。std::ostream& out2 = std::ofstream(""); 不会在标准 C++ 中编译。您可能正在使用 MSVC++(允许此类代码)?
  • 我在 Win7 32 上有 VS Express 2013
  • @downforme:我告诉过你。 MSVC++ 允许将此类代码作为编译器扩展。但是,此代码不是标准 C++。
【解决方案2】:

据我了解,您想使用out 关闭文件流?

您不需要明确关闭它。 std::fstream 是 RAII 对象,所以它会在封闭范围结束时自动关闭打开的文件。

当然,如果您现在确实需要关闭文件,您可以随时投射out

if( ptr = dynamic_cast<std::ofstream*>(out) ) {
    ptr->close();
}

【讨论】:

  • 那行得通。我有一个基类,它包含提供实际流并负责关闭的 ostream 和子类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 2022-09-18
  • 1970-01-01
相关资源
最近更新 更多