Moving std::clog in source to output file [duplicate]

て烟熏妆下的殇ゞ 提交于 2019-12-10 23:02:55

问题


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?


回答1:


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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/34618916/moving-stdclog-in-source-to-output-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!