Moving std::clog in source to output file [duplica

2019-07-15 05:08发布

This question already has an answer here:

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?

2条回答
祖国的老花朵
2楼-- · 2019-07-15 05:36

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;
}
查看更多
\"骚年 ilove
3楼-- · 2019-07-15 05:39

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.

查看更多
登录 后发表回答