简体   繁体   English

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

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

I'm writing a command line tool and I would like it to write to STDOUT by default, but write to a file if specified.我正在编写命令行工具,我希望它默认写入 STDOUT,但如果指定则写入文件。 I'm trying to do this in a way that keeps the interface for writing the output consistent by using an output stream.我正在尝试通过使用 output stream 使编写 output 的接口保持一致的方式来执行此操作。

This was my first idea:这是我的第一个想法:

#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;
}

I don't like the conditional deletion of the output stream. That makes me think there must be a better way to do the same thing.我不喜欢 output stream 的条件删除。这让我觉得一定有更好的方法来做同样的事情。

A simple way to do this is just write to standard output and let the user use shell redirection to send the output to a file, if desired.一种简单的方法是写入标准 output,如果需要,让用户使用 shell 重定向将 output 发送到文件。

If you want to implement this in your code instead, the most straightforward way I can think of would be to implement the body of your program in a function that accepts an output stream:如果您想在代码中实现它,我能想到的最直接的方法是在接受 output stream 的 function 中实现程序主体:

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

Then you can conditionally call this function with std::cout or a file stream:然后你可以有条件地用std::cout或文件 stream 调用这个 function:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM