4

Can I use an elsewhere opened

FILE* f = ...

thing to initialize some std::ostream instance? Like this (pseudocode):

FILE *f = ...;
std::ostream os;
os./*bind_to_f*/( f );    // HOW?
os << "Hello world" << std::endl;
towi
  • 21,587
  • 28
  • 106
  • 187

3 Answers3

4

FILE* and streams are C and C++ style I/O capabilities respectively. Since the C++ library doesn't always know about the implementation of the underlying C library there's no way to do this. Additionally consider, what would the ownership semantics be if you could do this?

Mark B
  • 95,107
  • 10
  • 109
  • 188
2

With GCC you can just pass the existing file descriptor to the constructor (ref):

FILE *f = ...;
std::ofstream os(fileno(f));

Constructor: ofstream::ofstream (int fd)

Make an ofstream for writing to a file that was already open, using file descriptor fd.

orlp
  • 112,504
  • 36
  • 218
  • 315
  • 1
    `FILE*` isn't a file descriptor. – Šimon Tóth Jul 18 '11 at 15:29
  • 1
    And using a file descriptor isn't standard, so I would advise against anything like this. – John Jul 18 '11 at 15:32
  • 1
    @Let_Me_Be: Woops, but `fileno(FILE*)` returns the fd from the file. – orlp Jul 18 '11 at 15:32
  • @John: This is GCC only, so no need to worry about the regular standard. Though I would prefer an all-standard solution too. – orlp Jul 18 '11 at 15:34
  • 2
    actually, I think I want to try this. I like portable code as well, yes, but in this case it might save me a couple of hundred lines. How bad can it be? http://xkcd.com/292/ ;-) – towi Jul 18 '11 at 16:45
  • How do you close this properly? You have two objects (`FILE *` and `ofstream`) referring to the same file descriptor. Although you might just want to ignore the error. But an `fclose(f)` is necessary to free memory and will interact with the `ofstream`. A call to `dup()` might help. – sstn Jul 05 '13 at 08:29
2

If you were to create a streambuf class that used a FILE* internally, you could do it. For example, HP OpenVMS seems to have a class like that.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274