Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect standard error to a string in 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?

like image 549
user1660675 Avatar asked Dec 07 '22 09:12

user1660675


1 Answers

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.

like image 79
iabdalkader Avatar answered Dec 22 '22 04:12

iabdalkader