Search code examples
cfreadstdio

in-memory FILE* (without disk access)


We have library which accepts FILE* (CImg). For performance reason we wish to handle data already in memory without accessing a disk. Target platform is windows which unfortunately does not support fmemopen (and funopen)

char* buf = new char[sz];

FILE *fp = fopen("C:\\test.dat", "wb");
int r = setvbuf(fp, buf, _IOFBF, sz);

r = fwrite(src_buf, 1, sz, fp);     // Here r contains right size


fseek(fp, 0, SEEK_END);
size_t sz2 = ftell(fp);             // sz2 contains right size as well
rewind(fp);

// Test (something like this actually is somewhere deep inside library)
char* read_buf = new char[sz];
r = fread(read_buf, 1, sz, fp);     // Zero!

Final fread() can't read anything... Any suggestions?


Solution

  • For our specific case we found CImg plugin doing the thing.

    As of a sample in an original question - at least MSVC runtime flushes written content to disk itself. So it isn't a valid replace for fmemopen()