将perror输出重定向到fprintf(stderr," ")

24

如果系统调用函数失败,我们通常使用perror输出错误消息。我想使用fprintf输出perror字符串,请问如何实现这样的功能:

fprintf(stderr, perror output string here);
1个回答

37
#include <errno.h>

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

注意:strerror函数在消息末尾不适用\n


谢谢Maverik。但是输出会和perror字符串完全相同吗? - RajSanpui
我正在做类似于这样的事情:fprintf(stderr, "LeakTracer: timer_settime 失败,无法设置计时器 (timer_trackStartTime): %s \n",strerror(errno); - RajSanpui
不完全相同。通常使用perror时,您会写:perror(“fopen”)。这将导致“fopen:<错误描述>”。在使用fprintf(stderr,“%s \ n”,strerror(errno))的情况下,您应该给出:<error_description>,因此如果您需要完全相同,请使用:fprintf(stderr,“fopen:%s \ n”,strerror(errno))。当然,您应该将“fopen”替换为您的函数名称 - maverik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接