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
{
int fd = ...;
__gnu_cxx::stdio_filebuf 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.
}