How to write to a memory buffer with a FILE*?

Viewed 46635

Is there any way to create a memory buffer as a FILE*. In TiXml it can print the xml to a FILE* but i cant seem to make it print to a memory buffer.

7 Answers

I guess the proper answer is that by Kevin. But here is a hack to do it with FILE *. Note that if the buffer size (here 100000) is too small then you lose data, as it is written out when the buffer is flushed. Also, if the program calls fflush() you lose the data.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *f = fopen("/dev/null", "w");
    int i;
    int written = 0;
    char *buf = malloc(100000);
    setbuffer(f, buf, 100000);
    for (i = 0; i < 1000; i++)
    {
        written += fprintf(f, "Number %d\n", i);
    }
    for (i = 0; i < written; i++) {
        printf("%c", buf[i]);
    }
}

You could use the CStr method of TiXMLPrinter which the documentation states:

The TiXmlPrinter is useful when you need to:

  1. Print to memory (especially in non-STL mode)
  2. Control formatting (line endings, etc.)

https://github.com/Snaipe/fmem is a wrapper for different platform/version specific implementations of memory streams

It tries in sequence the following implementations:

  • open_memstream.
  • fopencookie, with growing dynamic buffer.
  • funopen, with growing dynamic buffer.
  • WinAPI temporary memory-backed file.

When no other mean is available, fmem falls back to tmpfile()

Related