1

In C++11, is it possible to create an std::fstream corresponding to a FILE* C-standard-library file descriptor?

This would be the opposite of Getting a FILE* from a std::fstream .

and I'm specifically interested in an an std::ofstream, for writing to the file.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 1
    The short answer is "no". `std::fstream` is not required to be implemented with any knowledge of C I/O, or to use C I/O behind the scenes. – Peter Oct 02 '20 at 13:29
  • Well, the `FILE` struct is _implementation defined_. If yours has an fd, you can create a streambuf from that. – πάντα ῥεῖ Oct 02 '20 at 13:32
  • 1
    There's the `fileno()` to get the fd. It won't help. – rustyx Oct 02 '20 at 13:34
  • @rustyx Ooops, seems I confused that with a proprietary streambuf implementation we once had for that. You're right, there's no way from an fd. – πάντα ῥεῖ Oct 02 '20 at 13:48
  • It's sort of possible, but not out of the box. At one time, I've written a custom `FILE*` holding `struct nonstd::file_stream : std::ofstream` that would use the `FILE*` passed to the file_stream constructor to use (not to own / manage / destruct). I probably still have the code somewhere, but it's been about 20 years so I have no idea where its stowed away. On a ZIP disk somewhere (the old SCSI connected ZIP drives). – Eljay Oct 02 '20 at 14:11

0 Answers0