将ostream的内容复制到另一个ostream



我正在寻找一种方法将内容从一个ostream复制到另一个。我有以下代码:

std::ostringsteam oss;
oss << "stack overflow";
{
    //do some stuff that may fail
    //if it fails, we don't want to create the file below!
}
std::ofstream ofstream("C:\test.txt");
//copy contents of oss to ofstream somehow

任何帮助都是感激的!

怎么了

ofstream << oss.str();

?

如果你想使用ostream基类,那么这是不可能的,就ostream而言,所写的任何内容都将永远消失。您将不得不使用如下命令:

// some function
...
  std::stringstream ss;
  ss << "stack overflow";
  ss.seekg(0, ss.beg);
  foo(ss);
...
// some other function
void foo(std::istream& is)
{
  std::ofstream ofstream("C:\test.txt");
  ofstream << is.rdbuf();
}

最新更新