alf*_*lfC 2 c++ iostream ostream
我想写一个简单的程序,根据传递的选项,可执行文件将输出打印到屏幕或文件.该计划很简单.
#include<iostream>
int main(int argc, char* argv[]){
... process options...
std::ostream& out = ... // maybe std::cout, maybe a *new* std::ofstream;
out << "content\n";
}
Run Code Online (Sandbox Code Playgroud)
是否有一个很好的习惯用法std::cout在运行时替代或文件流?
我尝试了指针,但它太可怕了.我无法避免使用指针(更不用说稍后需要更难看的代码来删除指针).
#include<iostream>
#include<ofstream>
int main(int argc, char* argv[]){
std::string file = argc>1?argv[1]:"";
std::clog << "file: " << file << '\n';
// if there is no argument it will print to screen
std::ostream* out = (file=="")?&std::cout:(new std::ofstream(file)); // horrible code
*out << "content" << std::endl;
if(out != &std::cout) delete out;
}
Run Code Online (Sandbox Code Playgroud)
我不知道,也许C++流的某些功能允许这样做.也许我必须使用某种类型的擦除.我认为,问题在于std::cout它已经存在(是全局的),但是std::ofstream必须要创建.
我设法使用open并避免使用指针,但它仍然很难看:
int main(int argc, char* argv[]){
std::string file = argc>1?argv[1]:"";
std::clog << "file: " << file << '\n';
std::ofstream ofs;
if(file != "") ofs.open(file);
std::ostream& out = (file=="")?std::cout:ofs;
out << "content" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
过度工程化.
#include <iostream>
#include <fstream>
int main(int argc, char* argv[]) {
std::ofstream ofs(argc > 1 ? argv[1] : "");
std::ostream& os = ofs.is_open() ? ofs : std::cout;
// use os ...
}
Run Code Online (Sandbox Code Playgroud)
我的偏好是使用安装了合适的流缓冲区的流.这是直接输出到文件或std::cout:
#include <iostream>
#include <fstream>
int main(int ac, char* av) {
std::ofstream ofs;
if (1 < ac) {
ofs.open(av[1]);
// handle errors opening the file here
}
std::ostream os(file? file.rdbuf(): std::cout.rdbuf());
// use os ...
}
Run Code Online (Sandbox Code Playgroud)