Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect perror output to fprintf(stderr, " ")

Tags:

c

stderr

errno

In case a system call function fails, we normally use perror to output the error message. I want to use fprintf to output the perror string. How can I do something like this:

fprintf(stderr, perror output string here);
like image 376
RajSanpui Avatar asked Mar 30 '11 07:03

RajSanpui


People also ask

Does perror print stderr?

The perror() function prints an error message to stderr . If string is not NULL and does not point to a null character, the string pointed to by string is printed to the standard error stream, followed by a colon and a space.

Does perror print stdout?

perror() always does. There is no requirement that writing to either stdout or stderr writes to a terminal screen - that is up to the implementation (since not all systems even have a terminal).

Should I print to stderr?

It is good practice to redirect all error messages to stderr , while directing regular output to stdout . It is beneficial to do this because anything written to stderr is not buffered, i.e., it is immediately written to the screen so that the user can be warned immediately.


1 Answers

#include <errno.h>

fprintf(stderr, "%s\n", strerror(errno));

Note: strerror doesn't apply \n to the end of the message

like image 66
maverik Avatar answered Oct 19 '22 20:10

maverik