| 1 |
#include <unistd.h> |
| 2 |
#include <streambuf> |
| 3 |
#include <ios> |
| 4 |
|
| 5 |
class fdstreambuf: public std::streambuf |
| 6 |
{ |
| 7 |
public: |
| 8 |
fdstreambuf(int fd, size_t bufsize, std::ios::openmode mode = |
| 9 |
std::ios::in | std::ios::out) |
| 10 |
: |
| 11 |
fd(fd), |
| 12 |
bufsize(bufsize), |
| 13 |
buffer(new char[bufsize]) |
| 14 |
{ |
| 15 |
if (mode & std::ios::in) |
| 16 |
setg(buffer, buffer + bufsize, buffer + bufsize); |
| 17 |
} |
| 18 |
|
| 19 |
~fdstreambuf() |
| 20 |
{ |
| 21 |
delete buffer; |
| 22 |
} |
| 23 |
|
| 24 |
int underflow() // inspects the character |
| 25 |
{ |
| 26 |
if (gptr() < egptr()) |
| 27 |
return static_cast<unsigned char>(*gptr()); |
| 28 |
// return next char waiting in the buffer |
| 29 |
|
| 30 |
int |
| 31 |
nread = read(fd, buffer, bufsize); |
| 32 |
|
| 33 |
if (nread <= 0) // none read -> |
| 34 |
return EOF; |
| 35 |
|
| 36 |
setg(buffer, buffer, buffer + nread); |
| 37 |
return static_cast<unsigned char>(*gptr()); |
| 38 |
} |
| 39 |
|
| 40 |
private: |
| 41 |
int fd; |
| 42 |
size_t bufsize; |
| 43 |
char* buffer; |
| 44 |
}; |