streambuf

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <shlobj.h>
#include <sstream>
#include <streambuf>
#include <locale>
#include <cstdio>

template<class charT, class traits = std::char_traits<charT> >
class basic_outbuf : public std::basic_streambuf<charT, traits>
{
public:
int size()
{
return pptr() - gptr();
}


protected:
//virtual typename traits::int_type overflow(typename traits::int_type c) 
//{
// if (!traits::eq_int_type(c, traits::eof())) {
// c = std::toupper(c, getloc());


// std::cout << " overflow " << epptr() - pptr() << std::endl;


// if (putchar(c) == EOF) {
// return traits::eof();
// }
// }
//
// return traits::not_eof(c);
//}


//virtual std::streamsize xsputn(const char* s, std::streamsize num) {
// std::cout << "xsputn:" << s << std::endl;
// return 0;
//}
};


typedef basic_outbuf<char> outbuf_2;




class outbuf : public std::streambuf
{
protected:
static const int bufferSize = 10;
char buffer[bufferSize];


public:
outbuf() {
setp(buffer, buffer + (bufferSize-1));
}


virtual ~outbuf()
{
//sync();
}


protected:
int flushBuffer() {
int num = pptr() - pbase();
std::cout << "flushBuffer:" << buffer << " num:" << num << std::endl;

pbump(-num);


std::cout << "after pbump -num:" << pptr() - pbase() << std::endl;
return num;
}


virtual int_type overflow(int_type c)
{
if (c != EOF) {
*pptr() = c;
pbump(1);
std::cout << "after pbump 1:" << pptr() - pbase() << std::endl;
}


if (flushBuffer() == EOF) 
return EOF;


return c;
}


virtual int sync() {
if (flushBuffer() == EOF)
return -1;


return 0;
}


};


class inbuf : public std::streambuf
{
protected:
static const int bufferSize = 10;
char buffer[bufferSize];


public:
inbuf() {
setg(buffer+4, buffer+4, buffer+4);
}


protected:
virtual int_type underflow() {
if (gptr() < egptr()) {
return *gptr();
}


int numPutback;
numPutback = gptr() - eback();
if (numPutback > 4)
numPutback = 4;


std::memcpy(buffer+(4-numPutback), gptr() - numPutback, numPutback);


int num;
num = bufferSize - 4;


strncpy(buffer+4, "hello,world", bufferSize - 4);
setg(buffer+4 - numPutback, buffer+4, buffer+4+num);


return *gptr();
}
};




void test(int& val)
{
int v = val;
v = 111;
}




int _tmain(int argc, _TCHAR* argv[])
{
outbuf_2 ob;
std::ostream out(&ob);
out << "hello,world" << std::endl;

char buffer[32];
ob.sgetn(buffer, 32);
std::cout << ob.size() << std::endl;


// std::streambuf buf;
// std::ostream out(&buf);
// out << "hello, world";

// char buffer[32];
// buf.sgetn(buffer, 32);


return 0;

你可能感兴趣的:(streambuf)