C 中的字符串流 [英] String Stream in C

查看:31
本文介绍了C 中的字符串流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

print2fp(const void *buffer, size_t size, FILE *stream) {

 if(fwrite(buffer, 1, size, stream) != size)
  return -1;

 return 0;
}

如何将数据写入字符串流而不是文件流?

How to write the data into string stream instead of File stream?

推荐答案

posix 2008 标准中有一个非常简洁的函数:open_memstream().你像这样使用它:

There is a very neat function in the posix 2008 standard: open_memstream(). You use it like this:

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.
");
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"
", buffer);
free(buffer);

这篇关于C 中的字符串流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆