4

Is it possible to create an ofstream object from a given stdio file (old-style C file handle)? Preferably without closing and re-opening the file.

The purpose for this is I have a stdio file and a library I'm using takes a stream object.

sarnold
  • 102,305
  • 22
  • 181
  • 238
moinudin
  • 134,091
  • 45
  • 190
  • 216
  • Not portably I think... Otherwise check out http://stackoverflow.com/questions/109449/getting-a-file-from-a-stdfstream – parapura rajkumar Nov 10 '11 at 01:09
  • @par Not necessary to have it portable, this is for linux. – moinudin Nov 10 '11 at 01:10
  • 3
    Possible duplicate: [How to construct a c++ fstream from a POSIX file descriptor?](http://stackoverflow.com/q/2746168/440558) – Some programmer dude Nov 10 '11 at 01:16
  • If you're at liberty to modify the library, you could try something [like this](http://codereview.stackexchange.com/questions/4679/shared-ptr-and-file-for-wrapping-cstdio). – Kerrek SB Nov 10 '11 at 01:19
  • @JoachimPileborg In your cited example, one could just use `tempnam` instead and open the file by string. In any case, it's a Bad Idea becuase of buffering issues. – moshbear Nov 10 '11 at 01:31

1 Answers1

1

If using boost is an option, and the library takes std::basic_ostream (as opposed to an std::ofstream) you could use a File Descriptor Sink to wrap your file descriptor, construct a stream from of it, and pass it to your target library.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523