C++ FILE 不写入磁盘
我使用的库有很多写入 FILE 的函数,但似乎没有一个函数可以方便地将相同的数据转储到内存中的对象。有没有办法创建一个 FILE 对象(或覆盖它),将数据存储在内存中而不是写入磁盘 - 我想避免打开/写入/读取的性能影响文件一遍又一遍。
更新:根据罗布的建议,尝试字符串流:
ss.put(c);
std::string myval = ss.str();
printf("Value: %s\n after writing: %i length %lu\n",myval.c_str(),c, myval.length());
但是,现在尝试从字符串流中获取数据(二进制)让我陷入困境——如何获取我一直在添加的二进制数据?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
考虑安装
tmpfs
并让应用程序写入它。当然这只是*nix。Consider mounting a
tmpfs
and have the application write to it. Of course this is *nix only.https://github.com/Snaipe/fmem 似乎是一个便携式
fmemopenvoid*
。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 avoid*
that points to the memory where you data is.除了已经提到的 GNU 的
fmemopen()
之外,它在 POSIX 中称为 open_memstream,可以结合mmap()
(使用 MAP_ANONYMOUS)或任何其他将文件描述符返回到内存块的特定于操作系统的函数来获得类似的解决方案,和fdopen()
.编辑:那是错误的,mmap 不会创建文件描述符。
Beside the already mentioned GNU's
fmemopen()
, which is known in POSIX as open_memstream, similar solution can be obtained combiningmmap()
(using MAP_ANONYMOUS) or any other OS-specific function that returns a file descriptor to a block of memory, andfdopen()
.EDIT: that was wrong, mmap doesn't create a file descriptor.
GNU libc 有,例如,
fmemopen
,它将为您提供一个写入内存的FILE *
。在 Linux 系统上尝试man fmemopen
了解详细信息。我怀疑(但不确定)
fmemopen
是一个包装器,用于编排 @Cubbi 提到的mmap
/fdopen
方法。The GNU libc has, e.g.,
fmemopen
which will give you aFILE *
that writes to memory. Tryman fmemopen
on your Linux system for details.I suspect (but do not know for sure) that
fmemopen
is a wrapper that orchestrates themmap
/fdopen
approach mentioned by @Cubbi.如果您可以选择修改库,则可以使用 C++ 流而不是 C FILE 流。
如果您的旧库函数如下所示:
您可以将该代码替换为:
然后,在您的非库代码中,执行以下操作:
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:
you might replace that code with:
Then, in your non-library code, do something like:
如果您使用的是 Mac OS X 或 iOS,则无法访问 fmemopen。我在这里开源了一个解决方案:
http://jverkoey.github.com/fmemopen/
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/