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的值作为参数,并返回一个描述错误的字符串
/*rename.c*/
#include<stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc,char **argv)
{
char path[]="./first.c";
char newpath[] = "./second.c";
char newpathnot[] = "./gong/suo.c";
extern int errno;
if( rename(path,newpathnot) == 0)
{
printf("the file %s was moved to %s.",path,newpathnot);
}
else
{
printf("Can't move the file %s.\n",path);
printf("errno:%d\n",errno);
printf("ERR:%s\n",strerror(errno));
perror("Err");
}
if(rename(path,newpath) == 0)
printf("the file %s was moved to %s.\n",path,newpath);
else
{
printf("Can't move the file %s.\n",path);
printf("errno:%d\n",errno);
printf("ERR:%s\n",strerror(errno));
}
return 0;
}
gcc rename.c -o rename
./rename
Can't move the file ./first.c.
errno:2
ERR:No such file or directory
Err: No such file or directory
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语句!