Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make FILE* struct map to a buffer?

Tags:

c

file

buffer

I am working with some legacy code which uses something like this:

void store_data(FILE *file);

However, I don't want to store data on the disk, I want to store it in memory (char *buf). I could edit all of the code, but the code jumps all over the place and fwrite gets called on the file all over the place. So is there an easier way, for example that I can map a FILE* object to an (auto-growing) buffer? I do not know the total size of the data before-hand.

The solution has to be portable.

like image 299
orlp Avatar asked Feb 22 '12 19:02

orlp


1 Answers

There is no way to do this using only the facilities provided in the C standard. The closest you can come is

FILE *scratch = tmpfile();
...
store_data(scratch);
...
/* after you're completely done calling the legacy code */
rewind(scratch);
buf = read_into_memory_buffer(scratch);
fclose(scratch);

This does hit the disk, at least potentially, but I'd say it's your best bet if you need wide portability and can't modify the "legacy code".

In POSIX.1-2008, there is open_memstream, which does exactly what you want; however, this revision of POSIX is not yet widely adopted. GNU libc (used on Linux and a few others) has it, but it's not available on OSX or the *BSDs as far as I know, and certainly not on Windows.

like image 166
zwol Avatar answered Sep 16 '22 13:09

zwol