3

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?

James King
  • 31
  • 1
  • 4
  • 1
    You can't, not without also redirecting normal output (if you use redirection from outside of the program). The onbly way is to use another output stream, possibly a reference that you initialize either to the output file stream or `std::clog`. – Some programmer dude Jan 05 '16 at 18:41

2 Answers2

7

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;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • More generally with example here: http://www.cplusplus.com/reference/ios/ios/rdbuf/ – Steeve McCauley Mar 25 '19 at 14:13
  • What happens if one doesn't reset `std::clog` before exiting? Would that affect the system in any way? – thomthom Sep 27 '20 at 11:56
  • @thomthom, if anything is written to `std::clog` during the termination phase of the program, the program will run into undefined behavior. – R Sahu Jan 11 '23 at 18:26
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 and std::wclog control output to a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C output stream stderr, but, unlike std::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.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190