1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
/*
* Copyright (C) 2009 - 2010 René Rebe, ExactCODE GmbH, Germany.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2. A copy of the GNU General
* Public License can be found in the file LICENSE.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANT-
* ABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* Alternatively, commercial licensing options are available from the
* copyright holder ExactCODE GmbH Germany.
*/
#ifndef UTILITY__FDSTREAM_HH__
#define UTILITY__FDSTREAM_HH__
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <iostream>
namespace Utility {
class fdbuf : public std::streambuf
{
protected:
int fd;
/* output */
virtual int_type overflow(int_type c) {
if (c != EOF) {
char cc = c;
if (write(fd, &cc, 1) != 1)
return EOF;
}
else {
return EOF;
}
return c;
}
virtual std::streamsize xsputn(const char* s, std::streamsize num) {
return write(fd, s, num);
}
/* input */
char buffer[2];
virtual int_type underflow() {
if (gptr() < egptr())
return *gptr();
int numPutback = gptr() - eback();
if (numPutback > 1)
numPutback = 1;
buffer[0] = buffer[1];
int num = read(fd, &buffer[1], 1);
if (num <= 0)
return EOF;
setg(buffer + 1 - numPutback, buffer + 1, buffer + 1 + num);
return *gptr();
}
public:
fdbuf(int fd)
: fd(fd)
{
setg(buffer+1, buffer+1, buffer+1);
}
~fdbuf() {
close(fd);
}
};
class fdostream : public std::ostream
{
public:
fdostream(int fd)
: std::ostream(&buf), buf(fd) {
}
protected:
fdbuf buf;
};
class fdistream : public std::istream
{
public:
fdistream(int fd)
: std::istream(&buf), buf(fd) {
}
protected:
fdbuf buf;
};
class fdstream : public std::iostream
{
public:
fdstream(int fd)
: std::iostream(&buf), buf(fd) {
}
protected:
fdbuf buf;
};
}
#endif
|