Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 584
Abruzzo Forte e Gentile Avatar asked Jul 19 '12 10:07

Abruzzo Forte e Gentile


3 Answers

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.
}
like image 162
Maxim Egorushkin Avatar answered Oct 04 '22 12:10

Maxim Egorushkin


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

like image 4
Hampus Nilsson Avatar answered Oct 04 '22 12:10

Hampus Nilsson


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.

like image 4
Some programmer dude Avatar answered Oct 04 '22 10:10

Some programmer dude