3

I'm sorry if this is a question that's already come up, but I searched and couldn't find anything - is there a way in the C++ standard library to get an ostream (or an istream, depending on what you want) from a FILE*?

Something along the lines of

FILE* something;
auto out = hypothetical(something);
out << "Hello world" << std::endl;
Cubic
  • 14,902
  • 5
  • 47
  • 92
  • 1
    Some ideas [here](http://stackoverflow.com/questions/2746168/how-to-construct-a-c-fstream-from-a-posix-file-descriptor). – jrok Dec 17 '13 at 10:58
  • This shouldn't have been marked a duplicate question IMO. I mean this question is asking about an interface in the C++ input/output library for making a stream from a FILE*. The other question was about making a stream from a POSIX int file descriptor. While the answers there apply, they do so more in a related sense IMO than a duplicate sense. – Louis Langholtz Apr 26 '23 at 15:30
  • Incidentally perhaps, despite C++ recognizing [FILE*](https://en.cppreference.com/w/cpp/io/c/FILE), this is still (10 years after this was asked) a problem IMO in terms of the C++ standard input/output library. There are non standard interfaces in standard libc++ implementations like in gcc and clang that take POSIX file descriptors but not FILE* even though at least clang's implementation of streams uses FILE* under its hood. Which is also to say I share the OP's (Cubic's) interest in having a FILE* interface to C++ streams. – Louis Langholtz Apr 26 '23 at 15:36

1 Answers1

0

Depending on compiler, you probably can just do the following:

FILE* f = fopen(myFile, "w+");
std::fstream myStream(f);
myStream << "Hello World\n";
SashaZh
  • 122
  • 4
  • 1
    The "depending on compiler" part kinda makes this a non-option for me. I'm writing non-toy programs that have to work cross platform and cross compiler. – Cubic Dec 17 '13 at 12:32
  • Are you implying that all windows-only programs are "toy"? :) Anyway, I did some research, and it seems to me, that there's no cross-platform solution. – SashaZh Dec 17 '13 at 18:33
  • No, I'm implying I'm writing cross platform applications that aren't toys. – Cubic Dec 18 '13 at 10:00
  • This seems like a very reasonable extension/proposal to the C++ standard for `std::fstream` IMO. Sadly, it's not standard though at least through C++23. – Louis Langholtz Apr 26 '23 at 15:40