Is it possible to convert std::FILE* to iostream ?

Recommended Answers

All 4 Replies


there is no readily available facility in the standard library to do this. however, the library is designed to be extensible: so we can easily write our own stream/streambuf derived classes.

the Boost.Iostreams library does contain stream/streambuf derived classes which use a file descriptor/HANDLE. Boost is widely portable, so we could just use it instead of rolling out our own classes.

#include <stdio.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>

int main()
  FILE* file = fopen( "/tmp/file.txt", "w" ) ;
  int fd = fileno(file) ;

  using namespace boost::iostreams ;
  file_descriptor_sink fdsink(fd) ;
  stream< file_descriptor_sink > ofstm( fdsink ) ;

  std::ostream& std_ostm = ofstm ;
  std_ostm << "FILE* " << file << " fd: " << fd << '\n' ;

note: link with libboost_iostreams. eg.

>g++ -Wall -std=c++98 -pedantic -I /usr/local/include -L /usr/local/lib -lboost_iostreams

Is it possible to convert std::FILE* to iostream ?

Sure, using gnu's extension like it's described here :
file-to-iostream (c++)/

short extract :

FILE *f_pipe_in;
    // ... open the file, with whatever, pipes or who-knows ...
    // let's build a buffer from the FILE* descriptor ...
    __gnu_cxx::stdio_filebuf pipe_buf (f_pipe_in, ios_base::in);
    // there we are, a regular istream is build upon the buffer :
    istream stream_pipe_in (&pipe_buf);

Please don't drag up 2 year old threads. And it should be noted that in standard C++ no there is not a way.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.