create fstream from raw file descriptor
if I have a raw file descriptor, for example, a socket descriptor, is there any way to take that descriptor and pass it to any type of iostream object to create an iostream that reads and writes that file descriptor? file descriptors are a very common and portable part of most APIs, and if there is no way to do this, it seems like a huge oversight in the design of the iostreams library.
Correct way to use boost::iostreams::file_descriptor
I know this is an old thread but in case anyone else finds this:
Try using boost::iostreams::file_descriptor like this:
Code:
int fd = open("filename.txt", O_RDWR);
if (fd == -1) throw "Failed to open file";
io::stream<io::file_descriptor> stream(fd, true);
stream is now an std::iostream which you can both read and write to and of course fd is the file descriptor which you can lock.
Test code to create fstream from raw file desc/FILE*
Well, after the better part of a day of dabbling in the black arts of the various C++ streams classes, I've constructed the following test code that _seems_ to work, and I thought it would be nice to share. I'm not really sure it works properly, so I welcome review by those more steeped in the black arts.
Code:
#include <fstream>
#include <iostream>
#include <string>
#include <cmath>
#include <cassert>
#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <ext/stdio_filebuf.h>
using namespace std;
//std::ofstream stream_002;
int main(){
char *f_template;
f_template = new char(12);
memcpy(f_template, "/tmp/XXXXXX", 12);
int fd = mkstemp(f_template);
std::cout << "File Descriptor # is: " << fd << " file name = " << f_template <<std::endl;
// FILE *frp=fdopen(fd, "r"); // convert it into a FILE *
FILE *fwp=fdopen(fd, "w"); // convert it into a FILE *
// create a file buffer(NOT an iostream yet) from FILE *
// __gnu_cxx::stdio_filebuf<char> frb (frp, ios_base::in);
// Uses:
// stdio_filebuf (std::__c_file *__f, std::ios_base::openmode __mode, size_t __size=static_cast< size_t >(BUFSIZ))
__gnu_cxx::stdio_filebuf<char> fwb (fwp, std::ios_base::out);
// so fwb is of type stdio_filebuf
// istream my_temp_in (&frb); // create a stream from file buffer
std::iostream my_temp_stream_out (&fwb); // create a stream from file buffer
std::fstream my_temp_fstream;
// streambuf *bsbp;
// bsbp = my_temp_out.rdbuf();
// my_temp_fstream.rdbuf(bsbp);
my_temp_fstream.std::ios::rdbuf(my_temp_stream_out.rdbuf());
// my_temp_out << "iostream : Some test text" << std::endl;
// my_temp_out.flush();
my_temp_fstream << "fstream : Some test text" << std::endl;
my_temp_fstream.close();
// while(1){}
// Now take a look in your temp directory for the file
//name printed from the above cout statement. If you cat it out,
//you should see the "test text".
return 0;
}