Logo Search packages:      
Sourcecode: hitop version File versions

fdstream.h

#ifndef __fdstreamh__
#define __fdstreamh__

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <unistd.h>

using namespace std;

class fdobuf:public streambuf {
public:
  fdobuf(int fd):m_fd(fd){}
protected:
  int m_fd;
  virtual int overflow(int c){
    if(c!=EOF){
      char temp=c;
      if(write(m_fd,&temp,1)!=1) return EOF;
    }
    return c;
  }
  virtual streamsize xsputn(const char* s, streamsize len){
    return write(m_fd,s,len);
  }
};

class fdostream:public ostream{
public:
  fdostream (int fd):ostream(0),m_buf(fd){rdbuf(&m_buf);}
protected:
  fdobuf m_buf;
};

class fdibuf:public streambuf{
public:
  fdibuf(int fd):m_fd(fd){
    setg(m_buffer+s_PutBackSize,m_buffer+s_PutBackSize,m_buffer+s_PutBackSize);
  }
protected:
  int m_fd;
  static const int s_PutBackSize=4;
  static const int s_BufferSize=1024;
  char m_buffer[s_BufferSize+s_PutBackSize];
  virtual int underflow(){
    if(gptr()<egptr()) return int(*gptr());
    int numPutBack=gptr()-eback();
    if(numPutBack>s_PutBackSize) numPutBack=s_PutBackSize;
    memmove(m_buffer+s_PutBackSize-numPutBack,gptr()-numPutBack,numPutBack);
    int num=read(m_fd,m_buffer+s_PutBackSize,s_BufferSize);
    if(num<=0) return EOF;
    setg(m_buffer+s_PutBackSize-numPutBack,m_buffer+s_PutBackSize,m_buffer+s_PutBackSize+num);
    return int(*gptr());
  }
};

class fdistream : public istream {
public:
  fdistream(int fd):istream(0),m_buf(fd){rdbuf(&m_buf);}
protected:
  fdibuf m_buf;
};

#endif

Generated by  Doxygen 1.6.0   Back to index