Is there a (cross-platform) way to get a C FILE* handle from a C++ std::fstream ?
The reason I ask is because my C++ library accepts fstreams and in one particular function I’d like to use a C library that accepts a FILE*.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The short answer is no.
The reason, is because the
std::fstreamis not required to use aFILE*as part of its implementation. So even if you manage to extract file descriptor from thestd::fstreamobject and manually build a FILE object, then you will have other problems because you will now have two buffered objects writing to the same file descriptor.The real question is why do you want to convert the
std::fstreamobject into aFILE*?Though I don’t recommend it, you could try looking up
funopen().Unfortunately, this is not a POSIX API (it’s a BSD extension) so its portability is in question. Which is also probably why I can’t find anybody that has wrapped a
std::streamwith an object like this.This allows you to build a
FILEobject and specify some functions that will be used to do the actual work. If you write appropriate functions you can get them to read from thestd::fstreamobject that actually has the file open.