是否有用于写入 STDOUT 或文件的 C++ 习惯用法?

Is there a C++ idiom for writing to either STDOUT or a file?

我正在编写命令行工具,我希望它默认写入 STDOUT,但如果指定则写入文件。我正在尝试通过使用输出流使用于写入输出的接口保持一致的方式来执行此操作。

这是我的第一个想法:

#include <iostream>

int main(int argc, char* argv[]) {
  std::ostream* output_stream = &std::cout;

  // Parse arguments

  if (/* write to file */) {
    std::string filename = /* file name */;

    try {
      output_stream = new std::ofstream(filename, std::ofstream::out);
    } catch (std::exception& e) {
      return 1;
    }
  }

  // Possibly pass output_stream to other functions here.
  *output_stream << data;

  if (output_stream != &std::cout) {
    delete output_stream;
  }

  return 0;
}

我不喜欢输出流的条件删除。这让我觉得一定有更好的方法来做同样的事情。

一个简单的方法就是写入标准输出,如果需要,让用户使用 shell 重定向将输出发送到文件。

如果您想在代码中实现它,我能想到的最直接的方法是在接受输出流的函数中实现程序主体:

void run_program(std::ostream & output) {
    // ...
}

然后你可以用std::cout或文件流有条件地调用这个函数:

if (/* write to file */) {
    std::ofstream output{/* file name */};
    run_program(output);
} else {
    run_program(std::cout);
}