可以使用输出到FILE *的输出例程在C语言中构建字符串吗? [英] Can output routines that print to a FILE* be used to build a string in C?
问题描述
我对这个问题的答案是否感到很难过,但是我想把这个问题扔掉,以防任何人有任何聪明的主意。
I have a bad feeling that the answer to this question is "no", but I wanted to throw this out there in case anyone has any clever ideas.
我有一组输出例程,它们采用复杂的数据结构并以文本格式打印。他们的原型如下:
I have a set of output routines that take a complex data structure and print it in a textual format. They have prototypes like:
void print_mystruct(struct mystruct *s, FILE *stream)
我是这样写的,这样我就可以高效,缓冲地输出到终端,文件,到网络等。
I wrote it this way so that I can get efficient, buffered output to the terminal, to a file, to the network, etc.
不幸的是,我无法使用标准C99来使用相同的例程在内存中建立字符串。
Unfortunately, there's no way that I know of, using standard C99, that I can use these same routines to build up a string in memory.
所以我的问题是:
- 有什么聪明的方法可以有效地使用fputs(),fprintf( )等输出到字符串?
- 如果没有,是否有更好的范例可以有效地执行缓冲文件输出和字符串构建?我能想到的最好的办法就是使用vtable(而不是FILE *)拥有自己的结构。 vtable将具有一个输出函数,该函数可以追加到字符串或调用fwrite。但是后来我也必须创建printf包装器。
还有其他聪明的主意吗?
Any other clever ideas?
编辑:我发现 fmemopen()
是POSIX.1-2008的一部分(请参阅: fmemopen()),但并未得到广泛的支持,至少根据GNU libc手册而言。
I have discovered that fmemopen()
is part of POSIX.1-2008 (see: fmemopen()) but is not widely supported, at least according to the GNU libc manpage.
推荐答案
没有可移植的方法。 glibc系统(linux)具有 open_memstream / fmemopen ,其他系统可能没有有类似的东西。
There's no portable way of doing this. glibc systems(linux) have open_memstream/fmemopen , other systems might not have something like it.
可移植的方法是写入文件并将其读回字符串。 ,或将关注点分开。而不是实现
The portable way is to write to a file and read it back into a string. , or to separate the concerns. Instead of implementing
void print_mystruct(struct mystruct *s,FILE *f);
您想要实施
char *mystruct_2_str(struct mystruct *s);
动态分配字符串(或传入缓冲区),将其格式化为标准字符串函数(snprintf等),并让调用者决定是否将其写入FILE *
Which dynamically allocates a string(Or pass in a buffer), formats it to a string with standard string functions (snprintf etc.) and have the caller decide whether to write that to a FILE*
这篇关于可以使用输出到FILE *的输出例程在C语言中构建字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!