#include<cstdio>
#include<streambuf>
using namespace std;
#ifdef _MSC_VER
#include <io.h>
#else
#include<unistd.h>
#endif
class outbuf :public streambuf
{
protected:
const static int bufSize = 10;
char buffer[bufSize];
public:
outbuf()
{
setp(buffer, buffer + (bufSize - 1));//最后一个buffer字符数组空间做end位置,缓冲区逻辑上只占用bufSize - 1【预留一个位置做结尾位置】
}
virtual ~outbuf()
{
sync();
}
protected:
int flushbuf()//写至输出通道,回归起始位置
{
int num = pptr() - pbase();
if (write(1, buffer, num) != num)
return EOF;
pbump(-num);
return num;
}
int_type overflow(int_type c)//写满bufSize - 1缓冲区触发
{
if (c != EOF)
{
//在最后一个字符数组上写字符
*pptr() = c;
pbump(1);
}
if (flushbuf() == EOF)
return EOF;
return c;
}
virtual int sync()//同步输出通道与缓冲区 =>就是刷新
{
if(flushbuf() == EOF)
return -1;
return 0;
}
};
int main()
{
return 0;
}
自定义实现带缓冲区行为的streambuf
最新推荐文章于 2021-08-18 15:52:37 发布