制作一个文件指针读/写内存中的位置 [英] Make a file pointer read/write to an in-memory location

查看:227
本文介绍了制作一个文件指针读/写内存中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以做一个文件指针写入用的fopen一个文件()。但我可以做一个文件指针,这将使它因此调用为的fputc或fprintf中的功能,将数据写入内存的指针?这样的一个例子是在Java ByteArrayOutputStream。另外:我能在倒车时,凡库需要一个文件指针从读取运行它,所以我分配内存,并作出新的文件指针将从这个内存位置读取但当块的大小耗尽返回EOF? (ByteArrayInputStream的一样在Java中)。有没有办法在C这样做吗?例如:

  FILE * p = new_memory_file_pointer();
fprintf中(P,的Hello World \\ n!);
字符*数据= get_written_stuff(P);
的printf(%S,数据); //将打印的Hello World!

&放大器;&安培; / ||

 个char [] =的Hello World \\ n!;
FILE * p值= new_memory_file_pointer_read(S,sizeof的(多个));
字符*缓冲=(字符*)malloc的(1024 * sizeof的(炭));
的fread((无效*)缓冲液,1,sizeof的(S)中,p);
的printf(%S,缓冲区); //打印Hello World!


解决方案

如果您的操作系统提供 fmemopen
也许它会满足你的目的。

I can make a file pointer write to a file with fopen(). But can I make a file pointer that will make it so calling functions such as fputc or fprintf will write to a pointer in memory? An example of this is ByteArrayOutputStream in java. Also: could I run it in reverse, where a library needs a file pointer to read from, so I allocate memory, and make a new file pointer that will read from this memory location but return EOF when the size of the chunk runs out? (like ByteArrayInputStream in Java). Is there a way to do this in C? For example:

FILE *p = new_memory_file_pointer();
fprintf(p, "Hello World!\n");
char *data = get_written_stuff(p);
printf("%s", data); //will print Hello World!

&& / ||

char s[] = "Hello World!\n";
FILE *p = new_memory_file_pointer_read(s, sizeof(s));
char *buffer = (char *)malloc( 1024*sizeof(char) );
fread((void *)buffer, 1, sizeof(s), p);
printf("%s", buffer); //prints Hello World!

解决方案

If your operating system provides fmemopen, probably it will meet your purpose.

这篇关于制作一个文件指针读/写内存中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆