Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ FILE without writing to disk

I'm using a library that has quite a few functions that write to a FILE but none that seem to conveniently dump the same data to an object in memory. Is there any way to create a FILE object (or override it) that stores the data in memory instead of writing to disk -- I'd like to avoid the performance hit of opening/writing/reading from files over and over again.

UPDATE: per Rob's suggestion, trying stringstream:

ss.put(c);

std::string myval = ss.str();

printf("Value: %s\n after writing: %i length %lu\n",myval.c_str(),c, myval.length());

But, now trying to get the data (binary) out of the stringstream has me stuck -- how do I grab the binary data I've been adding?

like image 915
jnpdx Avatar asked May 02 '11 17:05

jnpdx


3 Answers

Beside the already mentioned GNU's fmemopen(), which is known in POSIX as open_memstream, similar solution can be obtained combining mmap() (using MAP_ANONYMOUS) or any other OS-specific function that returns a file descriptor to a block of memory, and fdopen().

EDIT: that was wrong, mmap doesn't create a file descriptor.

like image 80
Cubbi Avatar answered Nov 19 '22 15:11

Cubbi


The GNU libc has, e.g., fmemopen which will give you a FILE * that writes to memory. Try man fmemopen on your Linux system for details.

I suspect (but do not know for sure) that fmemopen is a wrapper that orchestrates the mmap/fdopen approach mentioned by @Cubbi.

like image 37
Ernest Friedman-Hill Avatar answered Nov 19 '22 16:11

Ernest Friedman-Hill


If you are on Mac OS X or iOS you don't have access to fmemopen. I've open sourced a solution here:

http://jverkoey.github.com/fmemopen/

like image 2
featherless Avatar answered Nov 19 '22 16:11

featherless