模拟文件指针 C++?

发布于 2024-11-04 12:53:24 字数 157 浏览 0 评论 0原文

我正在尝试从存档加载位图。我的位图类采用一个指向文件名的字符指针,然后加载它(如果它位于同一目录中)。位图加载类已经过充分测试,我不想过多地干扰它。问题是它使用文件指针来加载并执行所有文件操作。有没有什么方法可以模拟文件指针并实际从内存中的块中读取它?

抱歉,如果这是一个奇怪的问题。

I am trying to load a bitmap from an archive. The bitmap class I have takes a character pointer to a filename and then loads it if it is in the same directory. The bitmap loading class is well tested and I don't want to mess with it too much. Problem is it uses a file pointer to load and do all of its file manipulation. Is there any way to emulate a file pointer and actually have it read from a chunk in memory instead?

Sorry if this is a bizarre question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

长发绾君心 2024-11-11 12:53:24

您也可以使用管道。管道是一块内存,您可以使用文件原语在其中读取和写入。这基本上就是你想要的

(假设 POSIX 操作系统)

创建一个管道:

int p[2]; 
pipe(p); 

使用 fdopen() 将管道文件描述符转换为 FILE*

FILE *emulated_file = fdopen(p[0], "r"); 

然后将你想要的任何内容写入管道的写入端:

write(p[1], 17 ,"whatevereyouwant");

现在:

buf[32];
fread(&buf,1,32, emulated_file); 
cout<<buf<<endl;

将输出“whateveryouwant”。

You can also use a pipe. A pipe is a piece of memory where you can read and write using file primitives. Which is basically what you want

(Assuming POSIX Operating system)

create a pipe:

int p[2]; 
pipe(p); 

use fdopen() to turn the pipe file descriptor into a FILE*

FILE *emulated_file = fdopen(p[0], "r"); 

then write whatever you want to the write end of the pipe :

write(p[1], 17 ,"whatevereyouwant");

Now :

buf[32];
fread(&buf,1,32, emulated_file); 
cout<<buf<<endl;

willl output "whateveryouwant".

一杯敬自由 2024-11-11 12:53:24

重构它并创建采用与以前完全相同的参数的函数:如果您使用从磁盘读取的 fopen、fread 和 fseek,请创建从内存读取文件的 mopen、mread 和 mseek。您只需修复函数的名称即可。

它应该很容易,没有风险,并且代码最终不会看起来像一个肮脏的黑客。

Refactor it and create functions that takes the exact same parameters as before : If you used fopen, fread and fseek that read from disk, create mopen, mread and mseek that read file from memory. You'll only have to fix the name of the functions.

It should be easy without risk and code won't look like an dirty hack in the end.

并安 2024-11-11 12:53:24

查看 John Ratcliff 的文件接口 替换标准文件 I /O。它支持您需要的功能。

您仍然需要重构位图加载代码才能使用新界面。但是,此接口支持从磁盘上的文件或内存中的内存块加载(以及写入磁盘上的文件或可扩展的内存块)。

Check out John Ratcliff's File Interface replacement for standard file I/O. It supports the feature you need.

You'll still need to refactor the bitmap loading code to use the new interface. However, this interface supports loading from file on disk, or memory chunk in memory (as well as writing to file on disk, or to expandable memory chunks).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文