我在我的代码中有一个基本的调试消息,它打印一条关于调用哪个函数的消息。
#ifdef _DEBUG
std::clog << "message etc" << std::endl;
#endif如何重定向输出以将消息发送到文本文件?
发布于 2016-01-06 02:43:39
您可以设置与clog关联的缓冲区,该缓冲区使用要将其数据保存到的文件。
下面是一个演示该概念的简单程序。
#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;
}发布于 2016-01-06 02:45:15
如何重定向输出以将消息发送到文本文件?
由于远重定向是指程序代码之外的重定向,实际上这有点取决于您的shell语法。根据this reference的说法,std::clog通常绑定到std::cerr
将全局对象std::clog和std::wclog控件输出到与标准C输出流stderr相关联的实现定义类型(从std::streambuf派生)的流缓冲区,但与std::cerr/std::wcerr不同的是,这些流不会自动刷新,也不会自动与cout.绑定()。
例如,在bash中,你可以这样做
$ program 2> Logs.txt关于以编程方式重定向,您可以按照R Sahu's answer中提到的或currently marked duplicate中解释的那样进行。
https://stackoverflow.com/questions/34618916
复制相似问题