C++ FILE without writing to disk

[亡魂溺海] 提交于 2019-12-05 04:35:58

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.

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.

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/

If you have the option of modifying your library, you could 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 might replace that code with:

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 something like:

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

Consider mounting a tmpfs and have the application write to it. Of course this is *nix only.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!