Closed. This question is opinion-based. It is not currently accepting answers. Learn more
想改进这个问题吗更新问题,以便editing this post可以用事实和引用来回答。
三年前关闭。
有没有更好的方法来报告C语言中的错误例如,如果一个应该打开的文件不存在,我应该使用它吗?
if( fp == NULL )
{
      perror("Error: ");
      return(-1);
}

(从http://www.tutorialspoint.com/c_standard_library/c_function_perror.htm复制)

if( fp == NULL )
{
      fprintf(stderr, "Unable to open file for reading.\n");
      return(-1);
}

最佳答案

可以使用perror()或strerror获取错误消息如果要推迟错误消息的显示,或者要将消息记录到文件中,请保存errno并使用strerror(),因为perror只写入标准错误流,并且它使用全局errno集,如果在打印错误消息之前调用任何库函数,则errno可能随时更改。
使用saved errno的示例:

int savederrno;
....
if( fp == NULL )
{
  savederrno = errno; /* Save the errno immediately after an api/lib function or a system call */
  /*If you want to write to a log file now, write here using strerror and other library calls */
}

....
/* use strerror function to get the error message and write to log
    or write to std error etc*/

下面的手册页详细解释了错误报告。
http://www.gnu.org/software/libc/manual/html_node/Error-Messages.html
http://man7.org/linux/man-pages/man3/errno.3.html

关于c - perror()或自己的字符串输出到C中的stderr,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35597231/

10-12 16:14