日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

【C++进阶】C++创建文件/屏幕输出流类(将信息同时输出到文件和屏幕)

發(fā)布時間:2023/12/1 c/c++ 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【C++进阶】C++创建文件/屏幕输出流类(将信息同时输出到文件和屏幕) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在軟件的調試技術中,很重要的一個技術是將軟件運行過程中的一些信息寫入到“日志文件”中。但是同時還要將信息顯示到屏幕上,以方便程序員實時查看這些信息。
最簡單的一種辦法是這樣的:

std::ofstream output("debug.log", ios::out); output << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x; cout << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x;

不過,上面的代碼看起來很愚蠢。
下面使用streambuf構造一個自己的類,來實現(xiàn)這個功能

#include <streambuf> #include <iostream> #include <fstream>//Linux tee命令用于讀取標準輸入的數(shù)據,并將其內容輸出成文件。 //tee指令會從標準輸入設備讀取數(shù)據,將其內容輸出到標準輸出設備,同時保存成文件。 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、創(chuàng)建文件/屏幕輸出流對象teeteestream tee(std::cout, output);auto x = 1.1;tee << __FILE__ << ":" << __LINE__ << "\t" << "Variable x = " << x;return 0; }

效果:

總結

以上是生活随笔為你收集整理的【C++进阶】C++创建文件/屏幕输出流类(将信息同时输出到文件和屏幕)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。