从std :: cout或std :: ofstream(文件)获取std :: ostream

时间:2008-12-14 20:41:19

标签: c++ exception-handling iostream

如何将std::ostream绑定到std::coutstd::ofstream对象,具体取决于某个程序条件?尽管由于许多原因这无效,但我想实现在语义上等同于以下内容的东西:

std::ostream out = condition ? &std::cout : std::ofstream(filename);

我见过一些不例外的示例,例如来自http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html的示例:

int main(int argc, char *argv[])
{
  std::ostream* fp;                                           //1
  if (argc > 1)
     fp = new std::ofstream(argv[1]);                         //2
  else
     fp = &std::cout                                          //3

  *fp << "Hello world!" << std::endl;                         //4
  if (fp!=&std::cout) 
     delete fp;
}

有没有人知道一个更好的,异常安全的解决方案?

5 个答案:

答案 0 :(得分:61)

std::streambuf * buf;
std::ofstream of;

if(!condition) {
    of.open("file.txt");
    buf = of.rdbuf();
} else {
    buf = std::cout.rdbuf();
}

std::ostream out(buf);

将cout或输出文件流的基础streambuf关联到out。之后,您可以写入“out”,它将最终出现在正确的目的地。如果您只是希望std::cout的所有内容都进入文件,您也可以

std::ofstream file("file.txt");
std::streambuf * old = std::cout.rdbuf(file.rdbuf());
// do here output to std::cout
std::cout.rdbuf(old); // restore

第二种方法的缺点是它不是例外的安全。您可能想要编写一个使用RAII执行此操作的类:

struct opiped {
    opiped(std::streambuf * buf, std::ostream & os)
    :os(os), old_buf(os.rdbuf(buf)) { }
    ~opiped() { os.rdbuf(old_buf); }

    std::ostream& os;
    std::streambuf * old_buf;
};

int main() {
    // or: std::filebuf of; 
    //     of.open("file.txt", std::ios_base::out);
    std::ofstream of("file.txt");
    {
        // or: opiped raii(&of, std::cout);
        opiped raii(of.rdbuf(), std::cout);
        std::cout << "going into file" << std::endl;
    }
    std::cout << "going on screen" << std::endl;
}

现在,无论发生什么,std :: cout都处于干净状态。

答案 1 :(得分:25)

这是例外安全的:

void process(std::ostream &os);

int main(int argc, char *argv[]) {
    std::ostream* fp = &cout;
    std::ofstream fout;
    if (argc > 1) {
        fout.open(argv[1]);
        fp = &fout;
    }
    process(*fp);
}

编辑:Herb Sutter在文章Switching Streams (Guru of the Week)中解决了这个问题。

答案 2 :(得分:10)

std::ofstream of;
std::ostream& out = condition ? std::cout : of.open(filename);

答案 3 :(得分:1)

this post开始引用。

您可以应用类似的方法。

struct noop {
    void operator()(...) const {}
};
std::shared_ptr<std::ostream> of;
if (condition) {
    of.reset(new std::ofstream(filename, std::ofstream::out));
} else {
    of.reset(&std::cout, noop());
}

答案 4 :(得分:-3)

以下简单代码对我有用:

int main(int argc, char const *argv[]){   

    std::ofstream outF;
    if (argc > 1)
    {
        outF = std::ofstream(argv[1], std::ofstream::out); 
    }

    std::ostream& os = (argc > 1)? outF : std::cout;
}