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

♀尐吖头ヾ 提交于 2019-11-27 02:08:35

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

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*).

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.

There is no support of exposing file descriptor neither in standard C++ nor in libstdc++.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!