重定向和时间戳std :: cout

时间:2013-10-10 20:31:21

标签: c++ iostream

我需要将ofstream重定向到文件并为打印的每一行添加时间戳。 (它是记录系统的一部分)。

我有一个工作类可以做到这一点,但是当std :: endl被激活时它拒绝刷新文件。我对此有任何帮助。 (如果有更简单的方法可以告诉你)。

#include <iostream>
#include <streambuf>
#include <fstream>
#include <sys/time.h>
#include <cstring>
#include <memory>

class TimeStampBuf: public std::streambuf {
public:
    explicit TimeStampBuf(std::streambuf* dest) :
            _dest(dest),
            _isAtStartOfLine(true),
            _owner( NULL) {
    }
    explicit TimeStampBuf(std::ostream& dest) :
            _dest(dest.rdbuf()),
            _isAtStartOfLine(true),
            _owner(&dest) {
        _owner->rdbuf(this);
    }
    virtual ~TimeStampBuf() {
        if (_owner != NULL) {
            _owner->rdbuf(_dest);
        }
    }
protected:
    virtual int overflow(int ch) {
        if (_isAtStartOfLine) {
            char timebuff[30];
            timeval curTime;
            gettimeofday(&curTime, NULL);
            strftime(timebuff, sizeof(timebuff), "%Y-%m-%d %H:%M:%S:",
                    localtime(&curTime.tv_sec));
            sprintf(timebuff + strlen(timebuff), "%03u\t",
                    (unsigned int) curTime.tv_usec / 1000);
            _dest->sputn(timebuff, strlen(timebuff));
        }
        _isAtStartOfLine = ch == '\n';
        return _dest->sputc(ch);
    }
private:
    std::streambuf *_dest;
    bool _isAtStartOfLine;
    std::ostream *_owner;
};
class OutputRedirectAndStamp {
public:
    OutputRedirectAndStamp(std::string file, std::ostream &s = std::cout, std::ios::openmode mode = std::ios::out){
        _s=&s;
        _file=file;
        if(_file.size()){
            _mode=mode;
            _buf.open(file.c_str(),mode);
            _coutBuf = s.rdbuf((std::streambuf*)&_buf);
        }
        _tsb.reset(new TimeStampBuf(s));
    }
    void reopen(void){
        _tsb.reset();
        if(_file.size()){
            _s->rdbuf(_coutBuf); //reset to previous output
            _buf.close();
            _buf.open(_file.c_str(),_mode);
            _coutBuf = _s->rdbuf((std::streambuf*)&_buf);
        }
        _tsb.reset(new TimeStampBuf(*_s));
    }
    ~OutputRedirectAndStamp() {
        _tsb.reset();
        if(_file.size()){
            _s->rdbuf(_coutBuf); //reset to previous output
        }
    }
private:
    std::string _file;
    std::ios::openmode _mode;
    std::ostream *_s;
    std::filebuf _buf;
    std::streambuf *_coutBuf;
    std::unique_ptr<TimeStampBuf> _tsb;
};
int main()    //example main
{
    std::unique_ptr<OutputRedirectAndStamp> a;
    a.reset(new OutputRedirectAndStamp("test.txt",std::cout,std::ios::app | std::ios::out));

    std::cout<<"this is written to file"<<2<<std::endl;
    a->reopen();
    std::cout<<"this is written to file also"<<std::endl;
    a.reset();
    std::cout<<"this is written to stdout"<<std::endl;
    return 0;
}

1 个答案:

答案 0 :(得分:2)

当您刷新std::ostream时,会调用流缓冲区pubsync(),然后调用virtual函数sync()。如果您不覆盖sync(),则只会通过返回0来声明成功。在sync()覆盖中,您应该只调用保留的流缓冲区pubsync()

int TimeStampBuf::sync() {
    return _dest->pubsync();
}