我正在编写一个命令行工具,我希望它默认写入 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)
我不喜欢有条件删除输出流。这让我觉得一定有更好的方法来做同样的事情。
执行此操作的一个简单方法是写入标准输出,并让用户使用 shell 重定向将输出发送到文件(如果需要)。
如果您想在代码中实现这一点,我能想到的最直接的方法是在接受输出流的函数中实现程序主体:
void run_program(std::ostream & output) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后您可以有条件地使用std::cout文件流调用此函数:
if (/* write to file */) {
std::ofstream output{/* file name */};
run_program(output);
} else {
run_program(std::cout);
}
Run Code Online (Sandbox Code Playgroud)