Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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.

like image 292
Lodle Avatar asked Feb 12 '09 00:02

Lodle


3 Answers

There is a POSIX way to use memory as a FILE descriptor: fmemopen or open_memstream, depending on the semantics you want: Difference between fmemopen and open_memstream

like image 176
tbert Avatar answered Oct 30 '22 12:10

tbert


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]);
    }
}
like image 21
Antti Huima Avatar answered Oct 30 '22 13:10

Antti Huima


fmemopen can create FILE from buffer, does it make any sense to you?

like image 9
solotim Avatar answered Oct 30 '22 12:10

solotim