Accessing the UNIX file descriptor inside an fstream

Nathan Myers ncm@nospam.cantrip.org
Sat Sep 15 16:55:00 GMT 2001


On Fri, Sep 14, 2001 at 10:35:33PM -0700, Zack Weinberg wrote:
> On Fri, Sep 14, 2001 at 09:20:12PM -0700, Chris Rankin wrote:
> > I am (was) trying to port some C++ code from g++-2.95.3 to g++-3.0.1
> > and the showstopper problem was this single line:
> > 
> >   fcntl(m_file.rdbuf()->fd(), F_SETFD, FD_CLOEXEC);
> 
> Given the existence of the extended basic_filebuf constructor, I think
> it would be reasonable to provide an operator FILE *() member on
> basic_filebuf.  This would allow rewriting that as
> 
>     fcntl(fileno(static_cast<FILE *>(m_file.rdbuf())), F_SETFD, FD_CLOEXEC);
> 
> which fits with the way the standard library seems to work.
> 
> Chris is right, people do need this functionality and it doesn't serve
> our users to deny them it on pedantic conformance issues.

I completely agree that it should be possible to get the file descriptor
from a filebuf.  I would be very distressed, though, to find that one 
had to convert through a FILE* to get to it, and incensed to find an 
automatic conversion to FILE* in filebuf.  IMHO, filebuf::fd() is the 
right interface.

The Standard doesn't in any way imply that filebuf is built on top of
a C library FILE*, and I would hate to see the library documenting such
a dependency. The file descriptor, OTOH, is ultimately necessary to
implement filebuf on a POSIX system, so providing access to it creates
no new dependencies.  I would also welcome a way to bind a filebuf to an 
existing file descriptor (of course such a constructor must be marked
"explicit").

Aside from dependency issues, building in automatic conversions is
almost always a mistake, and would certainly be a mistake in this case.
Ordinary members are the right way to do this.

If, in addition to filebuf<>::fd(), somebody wanted to add a patch for
a filebuf<>::_libc_FILE_pointer() documented as unsupported, I would 
not object.

I don't see any need to reflect these interfaces up to the fstream
class template.

Nathan Myers
ncm at cantrip dot org



More information about the Libstdc++ mailing list