Search code examples
c++fstreamfile-descriptor

Retrieving file descriptor from a std::fstream


Possible Duplicate:
Getting a FILE* from a std::fstream

I am working on Linux and file descriptors are the main model in this OS.

I was wondering whether is there any library or any way to retrieve the native Linux file descriptor starting from a C++ std::fstream.

I thought about boost::iostream since there is a class called file_descriptor but I understood that its purpose is different from the one I want to achieve.

Do you know some way to do that?


Solution

  • You can go the other way: implement your own stream buffer that wraps a file descriptor and then use it with iostream instead of fstream. Using Boost.Iostreams can make the task easier.

    Non-portable gcc solution is:

    #include <ext/stdio_filebuf.h>
    
    {
        int fd = ...;
        __gnu_cxx::stdio_filebuf<char> fd_file_buf{fd, std::ios_base::out | std::ios_base::binary};
        std::ostream fd_stream{&fd_file_buf};
        // Write into fd_stream.
        // ...
        // Flushes the stream and closes fd at scope exit.
    }