Is it possible to create a C FILE object to read / write to memory

advertisements

I am using an API that takes a FILE * and am using that to create a data buffer in memory:

std::shared_ptr<FILE> f(tmpfile(), fclose);
write_to_file(f.get());
rewind(f.get());
auto data = make_file_buffer(f.get());
return data;

This works, but is slower than writing to a memory buffer.

Is it possible to get this to write to a memory file and avoid reading/writing to disk (like stdin/stdout/stderr read/write to the console)?

NOTE: I am using Linux, so have access to Linux and POSIX APIs.


Yes, this is possible, see fmemopen.