我的代碼中有一個基本的調試消息,它打印一條消息,指出調用了哪個函數。將源代碼中的std :: clog移動到輸出文件
#ifdef _DEBUG
std::clog << "message etc" << std::endl;
#endif
如何重定向輸出以將消息發送到文本文件?
我的代碼中有一個基本的調試消息,它打印一條消息,指出調用了哪個函數。將源代碼中的std :: clog移動到輸出文件
#ifdef _DEBUG
std::clog << "message etc" << std::endl;
#endif
如何重定向輸出以將消息發送到文本文件?
您可以設置與使用文件將其數據保存到的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;
}
如何輸出重定向到的信息發送到一個文本文件?
據重定向在程序代碼之外意味着,這取決於一點上你的shell語法其實。據this referencestd::clog
通常被綁定到std::cerr
:
的全局對象
std::clog
和std::wclog
控制輸出到執行定義類型(從std::streambuf
得到),與標準C的輸出流stderr關聯的數據流緩存器,但,與std::cerr/std::wcerr
不同,這些流不會自動刷新,也不會自動與cout綁定()。
例如,在bash,你會做這樣的事情
$ program 2> Logs.txt
關於重定向程序,你可以做到這一點作爲R Sahu's answer提到的,或在currently marked duplicate解釋。
你不能,也不能沒有重定向正常輸出(如果你使用程序外的重定向)。有效的方法是使用另一個輸出流,可能是初始化爲輸出文件流或'std :: clog'的引用。 –