我正在编写一个命令行工具,并且我希望它默认情况下写入STDOUT,但是如果指定则写入文件。我正在尝试以一种通过使用输出流使用于写入输出的接口(interface)保持一致的方式来执行此操作。
这是我的第一个主意:
#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);
}
关于c++ - 是否存在用于写入STDOUT或文件的C++习惯用法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63650783/