C ++ FILE without writing to disk

I use a library with many functions that are written in FILE , but none of them seem to be convenient to unload the same data into an object in memory. Is there a way to create a FILE object (or override it) that stores data in memory instead of writing to disk - I would like to avoid performance loss when opening / writing / reading from files again and again.

UPDATE: for every Rob clause 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 (binary) data from a string, I am stuck - how can I capture the binary data that I added?

+8
c ++ ios file-io memorystream
source share
6 answers

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

EDIT: this is wrong, mmap does not create a file descriptor.

+10
source share

GNU libc has, for example, fmemopen , which will give you FILE * , which writes to memory. Try man fmemopen on your Linux system for details.

I suspect (but don't know for sure) that fmemopen is a shell that organizes the mmap / fdopen approach mentioned by @Cubbi.

+5
source share

If you are on Mac OS X or iOS, you do not have access to fmemopen. I open the solution here:

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

+2
source share

If you have the opportunity to change your library, you can use C ++ streams instead of C FILE streams.

If your old library function looked like this:

 void SomeFun(int this, int that, FILE* logger) { ... other code ... fprintf(logger, "%d, %d\n", this, that); fputs("Warning Message!", logger); char c = '\n'; fputc(c, logger); } 

you can replace this code:

 void SomeFun(int this, int that, std::ostream& logger) { ... other code ... logger << this << ", " << that << "\n"; // or: logger << boost::format("%d %d\n") %this %that; logger << "Warning Message!"; char c = '\n'; logger.put(c); // or: logger << c; } 

Then in your non-library code, do the following:

 #include <sstream> std::stringstream logStream; SomeFun(42, 56, logStream); DisplayCStringOnGui(logStream.str().c_str()); 
+1
source share

Consider installing tmpfs and attach the application to it. Of course, this is just * nix.

0
source share

https://github.com/Snaipe/fmem is apparently a portable fmemopen in C. It gives you a FILE that you can write to, and when you are done, you get a void* which points to the memory in which fmemopen your data.

0
source share

All Articles