我基本上试图从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)
我想我已经解决了这个问题。
非常感谢任何帮助!谢谢!
答案 0 :(得分:0)
我使用filtering streambuf,它没有自己的缓冲,而是将数据传递给每个目的地的真正的streambuf(即,进行真正缓冲的)。这应该可以简化您的代码,让您专注于您真正关心的部分。