user3243499
user3243499

Reputation: 3161

How to retrieve contents from stderr in C?

I have an stderr statement having a sentence in it.

I want to get that content and push it to the standard output using printf().

fprintf(stderr, "Hello world!");

Now, I want to get this Hello World! and print it using printf() to the standard output.

Is it feasible ?

Upvotes: 0

Views: 805

Answers (1)

suresh
suresh

Reputation: 137

By default the stderr does not have any buffer. So, we need to set the buffer for the stderr.

you have to change the buffer for the stderr before any operation done on stderr.

To setting the buffer for the stderr, you can use setbuf() to set the buffer for the stderr.

Example :-

#include <stdio.h>

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

Output:-

Hello, world! 
Hello, world!

In this example, the variable buf contains what ever you written in stderr, it stored in the buf character array. Using that character array you can print that in stdout.

Upvotes: 1

Related Questions