perror()与strerror()的应用

来源:互联网 发布:java输入流和输出流 编辑:程序博客网 时间:2024/06/06 00:20
perror() 和 strerror() 以一种直观的方式打印出错误信息,对于调试程序和编写优秀的程序非常有用。
下面是perror() 与 strerror() 的使用范例及区别:

perror()原型:
#include <stdio.h>
void perror(const char *s);
其中,perror()的参数s 是用户提供的字符串。当调用perror()时,它输出这个字符串,后面跟着一个冒号和空格,然后是基于当前errno的值进行的错误类型描述。

strerror()原型:
#include <string.h>
char * strerror(int errnum);

这个函数将errno的值作为参数,并返回一个描述错误的字符串
[cpp] view plain copy
  1. /*rename.c*/  
  2.   
  3. #include<stdio.h>  
  4. #include <string.h>  
  5. #include <errno.h>  
  6.   
  7. int main(int argc,char **argv)  
  8. {  
  9.     char path[]="./first.c";  
  10.     char newpath[] = "./second.c";  
  11.     char newpathnot[] = "./gong/suo.c";  
  12.     extern int errno;  
  13.   
  14.     if( rename(path,newpathnot) == 0)  
  15.     {  
  16.         printf("the file %s was moved to %s.",path,newpathnot);  
  17.     }  
  18.     else  
  19.     {  
  20.         printf("Can't move the file %s.\n",path);  
  21.         printf("errno:%d\n",errno);  
  22.         printf("ERR:%s\n",strerror(errno));  
  23.         perror("Err");  
  24.     }  
  25.   
  26.     if(rename(path,newpath) == 0)  
  27.         printf("the file %s was moved to %s.\n",path,newpath);  
  28.     else  
  29.     {  
  30.         printf("Can't move the file %s.\n",path);  
  31.         printf("errno:%d\n",errno);  
  32.         printf("ERR:%s\n",strerror(errno));  
  33.     }  
  34.   
  35.     return 0;  
  36. }  
  37.   
  38.   
  39. gcc rename.c -o rename  
  40. ./rename  
  41.   
  42. Can't move the file ./first.c.  
  43. errno:2  
  44. ERR:No such file or directory  
  45. Err: No such file or directory  
  46. the file ./first.c was moved to ./second.c  

strerror()方法与perror()的用法十分相似。

    先谈谈perror()的用法,这个方法用于将上一条语句(方法)执行后的错误打印到标准输出上。一般情况下(没有使用重定向的话),就是输出到控制台上。

但是,如果我需要了解另外一个进程的某一个方法执行的错误,或者更briefly,我就希望将错误打印到一个文件里面,perror()就不太合适了!

为了实现我刚刚说到的要求,我们首先要将错误放到一个字符串里面。这个时候,strerror()就合适了!

strerror(errno)

    首先,系统会根据上一条语句的执行错误情况,将errno赋值.。关于这点,我们首先明白两点。第一,errno是一个系统变量,是不需要我们赋值或者声明的。第二,errno是一个int类型的变量,而且其中的值对应一种特定错误类型 
然后,关于streorror()本身,可以这么理解。顾名思义,streorror=string+error,就是将errno值翻译成描述错误类型的string语句!


转载自:http://blog.csdn.net/callinglove/article/details/8301789

0 0