Friday, February 18, 2011

getting file descriptor from file stream in linux

#include "iostream"
#include "ext/stdio_filebuf.h"
using namespace std;

int main()
{
ofstream *stream = new ofstream;
stream->open("test_file",ios::app);

typedef std::basic_filebuf filebuf_t;
filebuf_t* bbuf = dynamic_cast(stream->rdbuf());
if (bbuf != NULL) {
struct my_filebuf : public std::basic_filebuf {
int fd() { return this->_M_file.fd(); }
};

cout << "fd = " << static_cast(bbuf)->fd()<< endl;
}
}