开发者

Can I use a FILE* to initialize a C++ ostream object?

开发者 https://www.devze.com 2023-03-21 16:18 出处:网络
Can I use an elsewhere opened FILE* f = ... thing to initialize some std::ostream instance? Like this (pseudocode):

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消