Skip to content

Instantly share code, notes, and snippets.

@Staler2019
Forked from AndreLouisCaron/gist:1841061
Last active November 7, 2022 13:41
Show Gist options
  • Save Staler2019/f0aeaeac15fb585374fcb3e958332817 to your computer and use it in GitHub Desktop.
Save Staler2019/f0aeaeac15fb585374fcb3e958332817 to your computer and use it in GitHub Desktop.
C++ std::cerr redirect to file.
#define __TEST__
#ifdef __TEST__
#include <sstream>
// redirect outputs to another output stream.
class redirect_outputs {
std::ostream &myStream;
std::streambuf *const myBuffer;
public:
redirect_outputs(std::ostream &lhs, std::ostream &rhs = std::cout) : myStream(rhs), myBuffer(myStream.rdbuf())
{
myStream.rdbuf(lhs.rdbuf());
}
~redirect_outputs()
{
myStream.rdbuf(myBuffer);
}
redirect_outputs &operator=(const redirect_outputs &) = delete;
};
// redirect output stream to a string.
class capture_outputs {
std::ostringstream myContents;
const redirect_outputs myRedirect;
public:
capture_outputs(std::ostream &stream = std::cout) : myContents(), myRedirect(myContents, stream)
{
}
std::string contents() const
{
return (myContents.str());
}
};
#endif !__TEST__
/*-----------------------------------------------------------------------------------------------------*/
int main ( int argc, char ** argv )
{
#ifdef __TEST__
// Redirect standard error stream to log file.
std::ofstream log_file("stderr.log", std::ios::binary);
if (!log_file.is_open()) {
std::cerr
<< "Could not open log file for writing."
<< std::endl;
return (EXIT_FAILURE);
}
const redirect_outputs _(log_file, std::cerr);
#endif __TEST__
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment