LinuxC/C++编程基础(35) std::istream使用实例

来源:互联网 发布:淘宝助理价格怎么弄 编辑:程序博客网 时间:2024/05/21 11:32
#include <istream>
#include <iostream>
#include <fstream>
#define PACKETRECV_SIZE 20
typedef char Int8;
typedef unsigned char UInt8;
typedef signed int Int32;
typedef unsigned int UInt32;
using namespace std;
UInt8 _buff[PACKETRECV_SIZE]={0xad,0x83,0xce,0xb4,0x5d,0xf3,0x40,0x97,0xf0,0x70,
 0x8e,0x23,0xa4,0x56,0xb0,0x72,0x9b,0x77,0x90,0xcb};
UInt8 buffer[2]={0x40,0x5d};
class MemoryStreamBuf: public std::streambuf {
public:
        MemoryStreamBuf(char* pBuffer,UInt32 bufferSize);

public:


        UInt32    _written; 

        char*    _pBuffer;

        UInt32    _bufferSize;

};
MemoryStreamBuf::MemoryStreamBuf(char* pBuffer, UInt32 bufferSize): _pBuffer(pBuffer),_bufferSize(bufferSize),_written(0) {
        setg(_pBuffer, _pBuffer,_pBuffer + _bufferSize);
        setp(_pBuffer, _pBuffer + _bufferSize);
}
class MemoryIOS: public virtual std::ios
{
public:
        MemoryIOS(char* pBuffer,UInt32 bufferSize);
        ~MemoryIOS(){}
        MemoryStreamBuf* rdsbuf(){
                return &_buf;
        }
public:
        MemoryStreamBuf _buf;
};
MemoryIOS::MemoryIOS(char* pBuffer, UInt32 bufferSize):_buf(pBuffer, bufferSize) {
}
class MemoryInputStream: public MemoryIOS,public std::istream
{
public:
        MemoryInputStream(const char* pBuffer, UInt32 bufferSize);
};
MemoryInputStream::MemoryInputStream(const char* pBuffer, UInt32 bufferSize):

                MemoryIOS(const_cast<char*>(pBuffer), bufferSize),istream(rdsbuf())

{}

class BinaryReader{
public:
        BinaryReader(std::istream& istr);
        void read(UInt8& value);
        void read(Int8& value);
public:
        std::istream&  _istr;
};
BinaryReader::BinaryReader(std::istream& istr):

_istr(istr){}


void BinaryReader::read(UInt8& value){
        _istr.read((char*)&value,sizeof(value));
}
void BinaryReader::read(Int8& value){
        _istr.read(&value,sizeof(value));
}
int main () {
        MemoryInputStream _memory((const char*) buffer,2);
        BinaryReader reader(_memory);
        unsigned char a = 0;
        unsigned char b = 0;
        unsigned char d = 0;
        if(reader._istr.read((char*)&a,1).good()){
                printf("0x%.2x\n",a);
        }
        if(reader._istr.read((char*)&b,1).good()){
                printf("0x%.2x\n",b);
        }
        if(reader._istr.read((char*)&d,1).good()){
                printf("0x%.2x\n",d);
        }
        return 0;

}


转载请注明出处:山水间博客,http://blog.csdn.net/linyanwen99/article/details/8592857








原创粉丝点击