I'm looking for a method to copy the contents from one ostream
to another. I have the following code:
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
Any help is appreciated!
Anything wrong with
ofstream << oss.str();
?
If you want to use the ostream
base class then this isn't possible, as as far as an ostream
is concerned anything that is written is gone forever. You will have to use something like:
// 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();
}