Redirect standard error to a string in C

巧了我就是萌 提交于 2019-12-12 08:55:30

问题


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?


回答1:


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;
}

prints:

Hello, world! 
Hello, world!

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




回答2:


  1. Redirect stderr to stdout and pipe to your C program. See How to pipe stderr, and not stdout?
  2. Read from stdin in your C program, of course.

This is assuming stderr is coming from another program. If you want to capture all stderr output from your program and process, then in a separate thread listen for writes to stderr via fopen("/dev/stderr", "r").




回答3:


I gave an solution using C++ to redirect stdout and stderr to a function (called for each line). I know this was tagged as C, but the guts of my solution use the POSIX api.

See https://stackoverflow.com/a/25087408/364818



来源:https://stackoverflow.com/questions/14715493/redirect-standard-error-to-a-string-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!