24

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);
Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
RajSanpui
  • 11,556
  • 32
  • 79
  • 146

1 Answers1

37
#include <errno.h>

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

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

maverik
  • 5,508
  • 3
  • 35
  • 55
  • Thanks maverik. But the output will be exactly identical to perror string? – RajSanpui Mar 30 '11 at 07:24
  • So i am doing something like this: `fprintf(stderr, "LeakTracer: timer_settime failed to set timer (timer_trackStartTime): %s \n",strerror(errno);` – RajSanpui Mar 30 '11 at 07:30
  • Not exactly the same. When using perror usually you write: `perror("fopen")`. This results in `"fopen: "`. In case of `fprintf(stderr, "%s\n", strerror(errno))` you should give: ``, so if you need exactly the same, use: `fprintf(stderr, "fopen: %s\n", strerror(errno))`. Of course you should replace `fopen` by the name of your function – maverik Mar 30 '11 at 07:30