I have a basic debug message in my code that prints a message as to what function is called.
#ifdef _DEBUG
std::clog << "message etc" << std::endl;
#endif
How do I redirect the output to send the message to a textfile?
I have a basic debug message in my code that prints a message as to what function is called.
#ifdef _DEBUG
std::clog << "message etc" << std::endl;
#endif
How do I redirect the output to send the message to a textfile?
You can set the buffer associated with clog
that uses a file to save its data to.
Here's a simple program that demonstrates the concept.
#include <iostream>
#include <fstream>
int main()
{
std::ofstream out("test.txt");
// Get the rdbuf of clog.
// We need it to reset the value before exiting.
auto old_rdbuf = std::clog.rdbuf();
// Set the rdbuf of clog.
std::clog.rdbuf(out.rdbuf());
// Write to clog.
// The output should go to test.txt.
std::clog << "Test, Test, Test.\n";
// Reset the rdbuf of clog.
std::clog.rdbuf(old_rdbuf);
return 0;
}
How do I redirect the output to send the message to a textfile?
As far redirect means from outside the program code, it depends a bit on your shell syntax actually. According this reference std::clog
is usually bound to std::cerr
:
The global objects
std::clog
andstd::wclog
control output to a stream buffer of implementation-defined type (derived fromstd::streambuf
), associated with the standard C output stream stderr, but, unlikestd::cerr/std::wcerr
, these streams are not automatically flushed and not automatically tie()'d with cout.
So e.g. in bash you would do something like
$ program 2> Logs.txt
Regarding redirecting programmatically, you can do it as mentioned in R Sahu's answer, or explained in the currently marked duplicate.