[英]redirect std::cout to a custom writer
我想使用Mr-Edd的iostreams文章中的這個片段在某處打印std :: clog。
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
int main()
{
std::ostringstream oss;
// Make clog use the buffer from oss
std::streambuf *former_buff =
std::clog.rdbuf(oss.rdbuf());
std::clog << "This will appear in oss!" << std::flush;
std::cout << oss.str() << '\\n';
// Give clog back its previous buffer
std::clog.rdbuf(former_buff);
return 0;
}
所以,在一個主循環中,我會做類似的事情
while (! oss.eof())
{
//add to window text somewhere
}
這是ostringstream文檔,但我無法理解這樣做的最佳方法。 我有一個顯示文本的方法,我只想用ostringstream中的任何數據調用它。
將發送到std :: clog的任何內容重定向到我選擇的方法的最簡單/最好的方法是什么? 它是如上所述,並填寫while!eof部分(不確定如何),或者是否有更好的方法,比如通過在調用我的方法的地方重載一些'commit'運算符? 我喜歡快速簡單,我真的不想開始定義接收器,就像文章那樣使用boost iostreams - 這些東西已經超出了我的想象。
我鼓勵你看看Boost.IOStreams
。 它似乎很適合您的用例,使用它非常簡單:
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <iostream>
namespace bio = boost::iostreams;
class MySink : public bio::sink
{
public:
std::streamsize write(const char* s, std::streamsize n)
{
//Do whatever you want with s
//...
return n;
}
};
int main()
{
bio::stream_buffer<MySink> sb;
sb.open(MySink());
std::streambuf * oldbuf = std::clog.rdbuf(&sb);
std::clog << "hello, world" << std::endl;
std::clog.rdbuf(oldbuf);
return 0;
}
我想你想從ostream中取出文本而不是空的。 你可以這樣做:
std::string s = oss.str();
if(!s.empty()) {
// output s here
oss.str(""); // set oss to contain the empty string
}
如果這不是您想要的,請告訴我。
當然,更好的解決方案是移除中間人,並在你真正想要的地方有一個新的streambuf,無需稍后進行探測。 這樣的事情(注意,這適用於每個char,但streambufs中還有很多緩沖選項):
class outbuf : public std::streambuf {
public:
outbuf() {
// no buffering, overflow on every char
setp(0, 0);
}
virtual int_type overflow(int_type c = traits_type::eof()) {
// add the char to wherever you want it, for example:
// DebugConsole.setText(DebugControl.text() + c);
return c;
}
};
int main() {
// set std::cout to use my custom streambuf
outbuf ob;
std::streambuf *sb = std::cout.rdbuf(&ob);
// do some work here
// make sure to restore the original so we don't get a crash on close!
std::cout.rdbuf(sb);
return 0;
}
我需要從第三方庫中獲取std :: cout和std :: cerr的輸出,並使用log4cxx記錄它們,並仍然保留原始輸出。
這就是我提出的。 這非常簡單:
我用自己的類替換了ostream的舊緩沖區(比如std :: cout),以便我可以訪問寫入它的內容。
我還使用舊緩沖區創建一個新的std :: ostream對象,這樣我就可以繼續將輸出發送到我的控制台,除了將它發送到我的記錄器。 我覺得哪種方便。
碼:
class intercept_stream : public std::streambuf{
public:
intercept_stream(std::ostream& stream, char const* logger):
_logger(log4cxx::Logger::getLogger(logger)),
_orgstream(stream),
_newstream(NULL)
{
//Swap the the old buffer in ostream with this buffer.
_orgbuf=_orgstream.rdbuf(this);
//Create a new ostream that we set the old buffer in
boost::scoped_ptr<std::ostream> os(new std::ostream(_orgbuf));
_newstream.swap(os);
}
~intercept_stream(){
_orgstream.rdbuf(_orgbuf);//Restore old buffer
}
protected:
virtual streamsize xsputn(const char *msg, streamsize count){
//Output to new stream with old buffer (to e.g. screen [std::cout])
_newstream->write(msg, count);
//Output to log4cxx logger
std::string s(msg,count);
if (_logger->isInfoEnabled()) {
_logger->forcedLog(::log4cxx::Level::getInfo(), s, LOG4CXX_LOCATION);
}
return count;
}
private:
log4cxx::LoggerPtr _logger;
std::streambuf* _orgbuf;
std::ostream& _orgstream;
boost::scoped_ptr<std::ostream> _newstream;
};
然后使用它:
std::cout << "This will just go to my console"<<std::endl;
intercept_stream* intercepter = new intercept_stream(std::cout, "cout");
std::cout << "This will end up in both console and my log4cxx logfile, yay!" << std::endl;
對於log4cxx示例,您必須覆蓋overflow()和sync(),否則在收到第一個流后始終設置badbit。
請參閱: http : //groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/fd9d973282e0a402/a872eaedb142debc
InterceptStream::int_type InterceptStream::overflow(int_type c)
{
if(!traits_type::eq_int_type(c, traits_type::eof()))
{
char_type const t = traits_type::to_char_type(c);
this->xsputn(&t, 1);
}
return !traits_type::eof();
}
int InterceptStream::sync()
{
return 0;
}
如果您只想獲取ostringstream的內容,請使用其str()成員。 例如:
string s = oss.str();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.