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 ); 开发者_如何学Python // HOW?
os << "Hello world" << std::endl;
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?
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.
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.
精彩评论