创建,结果在一个字符串的文件*流 [英] Creating a FILE * stream that results in a string
问题描述
我在寻找一种方式在 FILE *
来的一些功能,使功能可以写入与 fprintf中传递code>。这是很容易,如果我想输出在磁盘上的实际的文件转起来,说。但我想反而是让所有的输出作为一个字符串(
的char *
)。我想那种API是:
I'm looking for a way to pass in a FILE *
to some function so that the function can write to it with fprintf
. This is easy if I want the output to turn up in an actual file on disk, say. But what I'd like instead is to get all the output as a string (char *
). The kind of API I'd like is:
/** Create a FILE object that will direct writes into an in-memory buffer. */
FILE *open_string_buffer(void);
/** Get the combined string contents of a FILE created with open_string_buffer
(result will be allocated using malloc). */
char *get_string_buffer(FILE *buf);
/* Sample usage. */
FILE *buf;
buf = open_string_buffer();
do_some_stuff(buf); /* do_some_stuff will use fprintf to write to buf */
char *str = get_string_buffer(buf);
fclose(buf);
free(str);
在的glibc 头似乎表明,一个文件可以设置钩函数来执行实际的读写。在我来说,我想我要的写勾串的拷贝追加到一个链表,并为那里是一个 get_string_buffer
函数,计算出总长度列表中分配内存它,并在正确的位置,然后再复制的每一项内容。
The glibc headers seem to indicate that a FILE can be set up with hook functions to perform the actual reading and writing. In my case I think I want the write hook to append a copy of the string to a linked list, and for there to be a get_string_buffer
function that figures out the total length of the list, allocates memory for it, and then copies each item into it in the correct place.
我的目标的东西,可以被传递给一个函数,如 do_some_stuff
,而不该功能需要知道任何其他比它有一个 FILE *
可写。
I'm aiming for something that can be passed to a function such as do_some_stuff
without that function needing to know anything other than that it's got a FILE *
it can write to.
有没有大概是这样一个现有的实现?这似乎是做一个有用的C-友好的事情 - 假设我是对有关文件
扩展
Is there an existing implementation of something like this? It seems like a useful and C-friendly thing to do -- assuming I'm right about the FILE
extensibility.
推荐答案
如果便携性是不是对你很重要,你可以采取的 fmemopen 和 open_memstream 。他们是GNU扩展,因此仅适用于glibc的系统。虽然看起来好像他们是POSIX.1-2008的一部分( fmemopen 和 open_memstream )。
If portability is not important for you, you can take a look on fmemopen and open_memstream. They are GNU extensions, hence only available on glibc systems. Although it looks like they are part of POSIX.1-2008 (fmemopen and open_memstream).
这篇关于创建,结果在一个字符串的文件*流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!