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.
There exists a (non-standard, looking for the reference now) C++ streambuf that is a layer on top of stdio, then it would be sufficient to constantly flush the stream buffer.
The automatic-flush part is portably accomplished using std::unitbuf
:
mysb << std::unitbuf;
Ahh, it's named stdio_filebuf
and comes with gcc's C++ library: __gnu_cxx::stdio_filebuf::stdio_filebuf constructor