How can I get a C++ streambuf object from a C FILE* so that it uses the FILE object’s buffer, avoiding both objects to manage separate buffers while pointing to the same underlying file.
It looks like there is no standard way of doing that.
Boost has a stream_buffer class that has a constructor taking a file descriptor, allowing the use C++features on a file opened with C code. For example:
boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_sink> mysb (fileno(myFileptr), boost::iostreams::never_close_handle));
myFileptr
being of type FILE*. The problem is that mysb
and the FILE object pointed at by myFileptr
will maintain separate buffers, so this is not an option…
Here is the context of my problem. I have to provide a dynamically linkable library with a C interface (all exported variables, function arguments and function return values must have C types), but the library is actually developed in C++.
If I export a function, internally using C++ stream facilities, with this prototype
Void MyExportedFunct( FILE* myfile)
And, I import the library in a C program:
int main()
{
FILE * fptr = fopen(“SomeFile”, "w");
fprintf(fptr, “Some data.”)
MyExportedFunct(fptr);
fprintf(fptr, “Some more data…”)
return 0;
}
I would like the data to be written to the file actually sent in the correct order (avoiding interleaved characters).
Any suggestion on how to achieve this, or for another approach, is welcome.