print2fp(const void *buffer, size_t size, FILE *stream) {
if(fwrite(buffer, 1, size, stream) != size)
return -1;
return 0;
}
如何将数据写入字符串流而不是文件流?
posix 2008 标准中有一个非常简洁的函数:open_memstream ()。你像这样使用它:
char* buffer = NULL;
size_t bufferSize = 0;
FILE* myStream = open_memstream(&buffer, &bufferSize);
fprintf(myStream, "You can output anything to myStream, just as you can with stdout.\n");
myComplexPrintFunction(myStream); //Append something of completely unknown size.
fclose(myStream); //This will set buffer and bufferSize.
printf("I can do anything with the resulting string now. It is: \"%s\"\n", buffer);
free(buffer);
使用sprintf
:http ://www.cplusplus.com/reference/cstdio/sprintf/
这是参考中的一个示例:
#include <stdio.h>
int main ()
{
char buffer [50];
int n, a=5, b=3;
n = sprintf(buffer, "%d plus %d is %d", a, b, a+b);
printf("[%s] is a string %d chars long\n", buffer, n);
return 0;
}
输出:
[5 plus 3 is 8] is a string 13 chars long
根据评论中的建议进行更新:
使用snprintf
它更安全(它可以防止缓冲区溢出攻击)并且更便携。
#include <stdio.h>
int main ()
{
int sizeOfBuffer = 50;
char buffer[sizeOfBuffer];
int n, a = 5, b = 3;
n = snprintf(buffer, sizeOfBuffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a string %d chars long\n", buffer, n);
return 0;
}
请注意,snprintf
的第二个参数实际上是允许使用的最大大小,因此您可以将其设置为低于 的值sizeOfBuffer
,但是对于您的情况,这将是不必要的。snprintf
只写入sizeOfBuffer-1
字符并使用最后一个字节作为终止字符。
这是snprintf
文档的链接:http ://www.cplusplus.com/reference/cstdio/snprintf/