There is no standard, but if you SHOULD do this, you will have to use something non-standard.
The GCC standard library includes the type streambuf, __gnu_cxx::stdio_filebufwhich can be constructed with FILE*(or a file descriptor), which you can use to replace streambuf fstream, or simply use with plain iostreamfor example
#include <stdio.h>
#include <ext/stdio_filebuf.h>
#include <fstream>
int main()
{
FILE* f = fopen("test.out", "a+");
if (!f)
{
perror("fopen");
return 1;
}
__gnu_cxx::stdio_filebuf<char> fbuf(f, std::ios::in|std::ios::out|std::ios::app);
std::iostream fs(&fbuf);
fs << "Test\n";
fs << std::flush;
fclose(f);
}
What should be noted about this:
stdio_filebufshould not go out of scope while iostreamstill referring to it- you need to manually close
FILE*, stdio_filebufwill not do this when building fromFILE* FILE*Be sure to close the stream before closing , otherwise there may be unwritten data sitting in the buffer stdio_filebuf, which cannot be written after closing FILE*.
source
share