在軟件的調試技術中,很重要的一個技術是將軟件運行過程中的一些信息寫入到“日志文件”中。但是同時還要將信息顯示到屏幕上,以方便程序員實時查看這些信息。
最簡單的一種辦法是這樣的:
std::ofstream output("debug.log", ios::out);
output << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x;
cout << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x;
不過,上面的代碼看起來很愚蠢。
下面使用streambuf構造一個自己的類,來實現這個功能
#include <streambuf>
#include <iostream>
#include <fstream>//Linux tee命令用于讀取標準輸入的數據,并將其內容輸出成文件。
//tee指令會從標準輸入設備讀取數據,將其內容輸出到標準輸出設備,同時保存成文件。
class teebuf : public std::streambuf
{
public:// Construct a streambuf which tees output to both input// streambufs.teebuf(std::streambuf* sb1, std::streambuf* sb2): sb1(sb1), sb2(sb2){}
private:// This tee buffer has no buffer. So every character "overflows"// and can be put directly into the teed buffers.virtual int overflow(int c){if (c == EOF){return !EOF;}else{int const r1 = sb1->sputc(c);int const r2 = sb2->sputc(c);return r1 == EOF || r2 == EOF ? EOF : c;}}// Sync both teed buffers.virtual int sync(){int const r1 = sb1->pubsync();int const r2 = sb2->pubsync();return r1 == 0 && r2 == 0 ? 0 : -1;}
private:std::streambuf* sb1;std::streambuf* sb2;
};class teestream : public std::ostream
{
public:// Construct an ostream which tees output to the supplied// ostreams.teestream(std::ostream& o1, std::ostream& o2);
private:teebuf tbuf;
};teestream::teestream(std::ostream& o1, std::ostream& o2): std::ostream(&tbuf), tbuf(o1.rdbuf(), o2.rdbuf())
{
}int main()
{std::ofstream output("debug.log");//1、創建文件/屏幕輸出流對象teeteestream tee(std::cout, output);auto x = 1.1;tee << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x;return 0;
}
效果: