将标准错误重定向到C中的字符串 [英] Redirect standard error to a string in C

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

问题描述

我希望能够将stderr重定向到C字符串,因为我需要在正在编写的程序中使用该字符串. 我想避免先写入文件(在硬盘上),然后再读取文件以获取字符串. 完成这项工作的最佳方法是什么?

I would like to be able to redirect stderr to a C string because I need to use the string in the program I'm writing. I would like to avoid writing to a file (on the hard drive) first then readings the file to get the string. What is the best way to get this done?

推荐答案

您可以只使用

You could just use setbuf() to change stderr's buffer:

#include <stdio.h>

int main(void)
{
    char buf[BUFSIZ];
    setbuf(stderr, buf);
    fprintf(stderr, "Hello, world!\n");
    printf("%s", buf);
    return 0;
}

打印:

Hello, world! 
Hello, world!

注意:您应该在对流执行任何操作之前更改缓冲区.

Note: you should change the buffer before any operation on the stream.

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

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