C 中的字符串流
print2fp(const void *buffer, size_t size, FILE *stream) {
if(fwrite(buffer, 1, size, stream) != size)
return -1;
return 0;
}
如何将数据写入字符串流而不是文件流?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
posix 2008 标准中有一个非常简洁的函数:open_memstream()。你像这样使用它:
There is a very neat function in the posix 2008 standard: open_memstream(). You use it like this:
使用
sprintf
:http://www.cplusplus.com/reference /cstdio/sprintf/这是参考中的示例:
输出:
根据注释中的建议进行更新:
使用
snprintf
因为它更安全(它可以防止缓冲区溢出攻击)并且更便携。请注意,
snprintf
的第二个参数实际上是允许使用的最大大小,因此您可以将其设置为低于sizeOfBuffer
的值,但是对于您的情况,这是不必要的。snprintf
仅写入sizeOfBuffer-1
个字符,并使用最后一个字节作为终止字符。以下是
snprintf
文档的链接:http://www .cplusplus.com/reference/cstdio/snprintf/Use
sprintf
: http://www.cplusplus.com/reference/cstdio/sprintf/Here's an example from the reference:
Output:
Update based on recommendations in comments:
Use
snprintf
as it is more secure (it prevents buffer overflow attacks) and is more portable.Notice that
snprintf
's second argument is actually the max allowed size to use, so you can put it to a lower value thansizeOfBuffer
, however for your case it would be unnecessary.snprintf
only writessizeOfBuffer-1
chars and uses the last byte for the termination character.Here is a link to the
snprintf
documentation: http://www.cplusplus.com/reference/cstdio/snprintf/