0

我基本上是在尝试从 wfilebuf 派生,因此我可以输出到文件并截取输出以将其打印到控制台/调试窗口,如下所示:http: //savingyoutime.wordpress.com/2009/04/ 21/和/或这里:http ://savingyoutime.wordpress.com/2009/04/22/40/

(古老的支持思想在这里: http: //www.horstmann.com/cpp/streams.txt

我几乎明白了,但我似乎无法同时写入基础文件并查看输入。

我覆盖了类似于第二个示例的 sync() 函数,但似乎 pbase() 和 pptr() 始终为 NULL,除非我使用 setp(...) 设置缓冲区,但这似乎破坏了文件输出。文件总是空的!

我对此的粗略尝试如下:

class LoggerBuffer : public wfilebuf {
// Functions
    public:
        LoggerBuffer();
        ~LoggerBuffer();
        void open(const wchar_t loggerFile[]);
        void close();
        int sync();
        int_type overflow(int_type c = EOF);
        void setState(int newState);
// Variables
    private:
        int currentState;
        static const int BUFFER_SIZE = 10;
        wchar_t buffer[BUFFER_SIZE];  
};

class LoggerStream : public wostream {
// Functions
    public:
         LoggerStream();
         ~LoggerStream();
         void open(const wchar_t loggerFile[] = 0);
         void close();
         void setState(int newState);
};

LoggerBuffer::LoggerBuffer() {
    wfilebuf::open("NUL", wios::out); currentState = 1;
}
LoggerBuffer::~LoggerBuffer() {
    wcout << "Destruction of LoggerBuffer" << endl;
}
void LoggerBuffer::open(const wchar_t loggerFile[]) {
    wcout << "LoggerBuffer Opening " << loggerFile << endl;
    close();
    wfilebuf* temp = wfilebuf::open(loggerFile, wios::out); //ios::out | ios::app | ios::trunc
    setp (buffer, buffer+(BUFFER_SIZE-1));
}
void LoggerBuffer::close() {
    wfilebuf::close();
}

int LoggerBuffer::sync() {
    wcout << "  Syncing ";
    int out_waiting = pptr() - pbase();
    wcout << out_waiting << " characters!";
    wcout << endl;
    wcout << "pptr(): " << (unsigned int)pptr() << endl;
    return wfilebuf::sync();
}
LoggerBuffer::int_type LoggerBuffer::overflow(int_type c) {
    wcout << "overflow! (" << (wchar_t)c << ")" << endl;
    if (c == EOF)
        return EOF;
    if (sync() == EOF)
        return EOF;
    return wfilebuf::overflow(c);
}
void LoggerBuffer::setState(int newState) {
    wcout << "New buffer state = " << newState << endl;
    currentState = newState;
}

LoggerStream::LoggerStream() : wostream(new LoggerBuffer), wios(0) {
}
LoggerStream::~LoggerStream() {
    delete rdbuf();
}
void LoggerStream::open(const wchar_t loggerFile[]) {
    wcout << "LoggerStream Opening " << loggerFile << endl;
    ((LoggerBuffer*)rdbuf())->open(loggerFile);
}
void LoggerStream::close() {
    ((LoggerBuffer*)rdbuf())->close();
}
void LoggerStream::setState(int newState) {
    wcout << "New stream state = " << newState << endl;
    ((LoggerBuffer*)rdbuf())->setState(newState);
}

完全披露:我之前问过一个类似的问题:Simple wostream logging class (with custom stream manipulators)

我想我已经解决了这个问题。

任何帮助是极大的赞赏!谢谢!

4

1 回答 1

0

我会使用一个过滤 streambuf,它自己不缓冲,而是将数据传递给每个目的地的真正的 streambuf(即,一个真正缓冲的)。这应该会大大简化您的代码,并让您专注于您真正关心的部分。

于 2010-11-13T08:42:19.163 回答