I think it is doable and desirable. i even was of the impression it would already work,but at least not as of what is in the std.
issues:
- [...] should adoption also work from a FILE*?
- can there be destruction without close?
POSIX defines fdopen(), which takes ownership of a low level file descriptor and returns a FILE* with which a user can perform buffered I/O. There doesn't appear to be a similar feature in C++, though non-standard workarounds exist, such as __gnu_cxx::stdio_filebuf.
Are there issues that would block standardisation of such a facility? Perhaps it's because fdopen() is part of POSIX rather than ISO C, hence file descriptors themselves may not be universally portable.
Paul: The feature "turn a file descriptor into a FILE" already exists in both C and C++, on POSIX platforms; the POSIX-standard facility is called `fdopen`.
File descriptors are a POSIX-standard thing. File descriptors don't exist, per se, on non-POSIX platforms. So the situation re "turn a file descriptor into a FILE" is already in the best possible state it could ever be in.
However, then there's the next step: "turn a FILE into an ifstream, ofstream, or fstream." These are things that exist in every standard C++ implementation, because the C++ standard defines both `FILE` (cstdio) and iostreams. It would be quite reasonable to propose a way to convert a `FILE` into an `{if,of,f}stream`, and/or vice versa.
However, you'll have to figure out what is the right API for this. POSIX uses plain old `int` for all kinds of file descriptors, regardless of readability/writeability. C and C++ use `FILE*` for all kinds of files, regardless of readability/writeability. But the C++ iostreams library uses different types — std::istream for readable files, std::ostream for writeable files. What happens if I do
FILE *fp = fopen("hello.txt", "r");
std::ofstream out = std::ofstream(std::from_file, fp);
Does this throw an exception? Is it library UB? A proposal would have to specify this kind of thing.
Another thing you'll need to figure out — and probably by actually trying to implement this in a real library or two, not just on paper — is whether it's even possible to create a plain `std::ofstream` from a `FILE`, or whether you really need to create a whole new derived class, e.g. `std::ofilestream` (by analogy to `ostringstream`). And then you'll have to decide whether an `ofilestream` IS-AN `ofstream` or merely an `ostream`. See