C++ 如何使用 FILE* 写入内存缓冲区?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/539537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write to a memory buffer with a FILE*?
提问by Lodle
Is there any way to create a memory buffer as a FILE*. In TiXml it can print the xml to a FILE* but i cant seem to make it print to a memory buffer.
有没有办法将内存缓冲区创建为 FILE*. 在 TiXml 中,它可以将 xml 打印到 FILE*,但我似乎无法将其打印到内存缓冲区。
回答by tbert
There is a POSIX way to use memory as a FILE
descriptor: fmemopen
or open_memstream
, depending on the semantics you want: Difference between fmemopen and open_memstream
有一种 POSIX 方法可以将内存用作FILE
描述符:fmemopen
或open_memstream
,具体取决于您想要的语义:fmemopen 和 open_memstream 之间的区别
回答by Antti Huima
I guess the proper answer is that by Kevin. But here is a hack to do it with FILE *. Note that if the buffer size (here 100000) is too small then you lose data, as it is written out when the buffer is flushed. Also, if the program calls fflush() you lose the data.
我想正确的答案是凯文。但是这里有一个技巧可以用 FILE * 来做到这一点。请注意,如果缓冲区大小(此处为 100000)太小,则会丢失数据,因为在刷新缓冲区时会写出数据。此外,如果程序调用 fflush() 您会丢失数据。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
FILE *f = fopen("/dev/null", "w");
int i;
int written = 0;
char *buf = malloc(100000);
setbuffer(f, buf, 100000);
for (i = 0; i < 1000; i++)
{
written += fprintf(f, "Number %d\n", i);
}
for (i = 0; i < written; i++) {
printf("%c", buf[i]);
}
}
回答by solotim
fmemopen can create FILE from buffer, does it make any sense to you?
fmemopen 可以从缓冲区创建 FILE,这对您有意义吗?
回答by sambowry
I wrote a simple example how i would create an in-memory FILE:
我写了一个简单的例子,我将如何创建一个内存文件:
#include <unistd.h>
#include <stdio.h>
int main(){
int p[2]; pipe(p); FILE *f = fdopen( p[1], "w" );
if( !fork() ){
fprintf( f, "working" );
return 0;
}
fclose(f); close(p[1]);
char buff[100]; int len;
while( (len=read(p[0], buff, 100))>0 )
printf(" from child: '%*s'", len, buff );
puts("");
}
回答by Kevin Loney
You could use the CStrmethod of TiXMLPrinterwhich the documentation states:
您可以使用文档说明的TiXMLPrinter的CStr方法:
The TiXmlPrinter is useful when you need to:
- Print to memory (especially in non-STL mode)
- Control formatting (line endings, etc.)
当您需要执行以下操作时,TiXmlPrinter 很有用:
- 打印到内存(尤其是在非 STL 模式下)
- 控制格式(行尾等)