重构它并创建与以前完全相同的参数:如果你使用从磁盘读取的fopen,fread和fseek,则创建从内存中读取文件的mopen,mread和mseek.您只需要修复函数的名称.
它应该很容易没有风险,代码最终看起来不像是一个肮脏的黑客.
您也可以使用管道。管道是一块内存,您可以使用文件原语在其中读取和写入。这基本上就是你想要的
(假设 POSIX 操作系统)
创建一个管道:
int p[2];
pipe(p);
Run Code Online (Sandbox Code Playgroud)
使用 fdopen() 将管道文件描述符转换为FILE*
FILE *emulated_file = fdopen(p[0], "r");
Run Code Online (Sandbox Code Playgroud)
然后将您想要的任何内容写入管道的写入端:
write(p[1], 17 ,"whatevereyouwant");
Run Code Online (Sandbox Code Playgroud)
现在 :
buf[32];
fread(&buf,1,32, emulated_file);
cout<<buf<<endl;
Run Code Online (Sandbox Code Playgroud)
将输出“whateveryouwant”。