Retrieving file descriptor from a std::fstream [duplicate]

Solution 1:

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.
}

Solution 2:

There is no (standard) way to extract the file number from an std::fstream since the standard library does not mandate how file streams will be implemented.

Rather, you need to use the C file API if you want to do this (using FILE*).

Solution 3:

There is no official way to get the private file handle of a file stream (or actualy a std::basic_filebuf), just because it should be portable and discourage use of platform-specific functions.

However, you can do ugly hack like inheriting std::basic_filebuf and from that try to pry out the file handle. It's not something I recommend though as it will probably break on different versions of the C++ library.