C ++文件不写入磁盘 [英] C++ FILE without writing to disk
问题描述
我正在使用一个函数库,它有很多函数可以写入 FILE
,但是没有一个函数可以方便地将相同的数据转储到内存中的对象。有没有办法创建一个 FILE
对象(或覆盖它),而不是写入磁盘的数据存储在内存中 - 我想避免性能击中
更新:每个Rob的建议,尝试stringstream:
ss.put(c);
std :: string myval = ss.str();
$ b printf(Value:%s \\\
写完之后:%i length%lu \\\
,myval.c_str(),c,myval.length());
但是,现在试图从stringstream中获取数据我已经添加了二进制数据吗?
除了已经提到的GNU的 fmemopen )
,这在POSIX中被称为 open_memstream ,类似的解决方案可以结合 mmap()
(使用MAP_ANONYMOUS)或任何其他操作系统特定的函数,返回一个文件描述符到一块内存,编辑:这是错误的,mmap不会创建一个文件描述符。
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?
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.
这篇关于C ++文件不写入磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!