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

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

Leave a Comment