小编jtp*_*mer的帖子

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

我正在编写一个命令行工具,我希望它默认写入 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;
}
Run Code Online (Sandbox Code Playgroud)

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

c++ io

2
推荐指数
1
解决办法
876
查看次数

标签 统计

c++ ×1

io ×1