我正在寻找一种方法将内容从一个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();
}