tags:

views:

89

answers:

3

I am facing a problem where the C library exposes only an interface that writes the data to a C FILE structure. This means all the data get saved to disk. I want this library to save the data to memory instead.

Is there a way to emulate FILE structure in my code and make it save the data in memory instead? I imagine FILE has various pointers to functions and I could write my own functions and make them allocate memory and on fwrite write the data to memory.

Can this be done?

Thanks, Boda Cydo.

+2  A: 

You can have a look at fmemopen.

Scharron
+1  A: 

On a UNIX system, you can use fdopen(3) to get a FILE* that uses a stream you previously opened. Then all you have to do is write some code to read from the other side of that pipe and shovel it into memory.

Variable Length Coder
I like this solution, but it's not so easy. It will require either threads or forking and using shared memory.
R..
+3  A: 

A portable solution would be to use fmemopen or open_memstream if these functions are available (they've been part of GNU libc for a long time and they were added to POSIX in 2008) and simply write to a temporary file then read back into memory if they're not.

R..