Wrap C style files in a C ++ stream

For a project, I MUST read / write using a C style file type. This can be a regular FILE, or a gzfile version in C, etc. I will still enjoy using C ++ streams. Is there a stream class that redirects to internal operations of a C-style file? So, myfile << hex << myinteventually becomes fprintf("%a", myint)or something like that?

+4
source share
2 answers

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*.
+3
source

streambuf, C. ++ ( , ), .

, << fprintf(file, ...): sprintf(buf, ...); fwrite(file, buf).

+1

All Articles