There's nothing provided for this in the standard. In a good
implementation of IOStream, there should be some additional,
implementation specific constructors for std::filebuf
, which
take a system file descripter (whose type will depend on the
system), and create a filebuf from that. If not, you'll have to
create your own streambuf. This can be more or less difficult,
depending on what you need: if you're just need a simple,
uni-directional stream (read or write, but not both), with no
support for seeking and no code translation on input, it's
relatively simple. (But you still have to be familiar with the
system level requests, like read
or write
.) If you want to
support everything that filebuf
does, it is significantly more
complicated.
EDIT:
Just thought I'd add an example. Since you speak of bash
,
I'll suppose Unix:
class FdStreambuf : public std::streambuf
{
int myFd;
char buffer[1024];
bool writeBuffer()
{
int len = pptr() - pbase();
return len == 0 || write( myFd, pptr(), len ) == len;
}
protected:
int overflow( int ch )
{
int results = ch == traits::eof() ? 0 : ch;
if ( pbase() != NULL ) {
if ( ! writeBuffer() ) {
results = traits::eof();
}
}
setp( buffer, buffer + sizeof( buffer ) );
sputc( ch );
return ch;
}
int sync()
{
return writeBuffer() ? 0 : -1;
}
public:
FdStreambuf( int fd ) : myFd( fd ) {}
int close()
{
sync();
return ::close( myFd );
}
};
class FdOStream : private FdStreambuf, public std::ostream
{
public:
FdOStream( int fd )
: FdStreambuf( fd )
, std::ostream( this )
{
}
void close()
{
if ( FdStreambuf::close() != 0 ) {
setstate( std::ios_base::badbit );
}
}
};
(I think that's all that's necessary, but it's possible I've
forgotten something.)