如何使用FILE *写入内存缓冲区?

有什么方法可以将内存缓冲区创建为FILE *。在TiXml中,它可以将xml打印到FILE *,但是我似乎无法使其打印到内存缓冲区。



慕妹3146593
浏览 923回答 3
3回答

梦里花落0921

有一种使用内存作为FILE描述符的POSIX方法:fmemopen或open_memstream,具体取决于您要使用的语义:fmemopen和open_memstream之间的区别

茅侃侃

我猜正确的答案是凯文。但是这里有一个使用FILE *的技巧。请注意,如果缓冲区大小(此处为100000)太小,则会丢失数据,因为刷新缓冲区时会将其写出。另外,如果程序调用fflush(),则会丢失数据。#include <stdio.h>#include <stdlib.h>int main(int argc, char **argv){&nbsp; &nbsp; FILE *f = fopen("/dev/null", "w");&nbsp; &nbsp; int i;&nbsp; &nbsp; int written = 0;&nbsp; &nbsp; char *buf = malloc(100000);&nbsp; &nbsp; setbuffer(f, buf, 100000);&nbsp; &nbsp; for (i = 0; i < 1000; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; written += fprintf(f, "Number %d\n", i);&nbsp; &nbsp; }&nbsp; &nbsp; for (i = 0; i < written; i++) {&nbsp; &nbsp; &nbsp; &nbsp; printf("%c", buf[i]);&nbsp; &nbsp; }}

狐的传说

我写了一个简单的示例,说明如何创建内存文件:#include <unistd.h>&nbsp;#include <stdio.h>&nbsp;int main(){&nbsp; int p[2]; pipe(p); FILE *f = fdopen( p[1], "w" );&nbsp; if( !fork() ){&nbsp; &nbsp; fprintf( f, "working" );&nbsp; &nbsp; return 0;&nbsp; }&nbsp; fclose(f); close(p[1]);&nbsp; char buff[100]; int len;&nbsp; while( (len=read(p[0], buff, 100))>0 )&nbsp; &nbsp; printf(" from child: '%*s'", len, buff );&nbsp; puts("");}
打开App,查看更多内容
随时随地看视频慕课网APP