err -x perror() strerror()

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

strerror()原型:
#include <string.h>
char * strerror(int errnum);
这个函数将errno的值作为参数,并返回一个描述错误的字符串

 1 #include<stdio.h> 
 2 #include <string.h> 
 3 #include <errno.h> 
 4 
 5 int main(int argc,char **argv) 
 6 { 
 7 char path[]="./first.c"; 
 8 char newpath[] = "./second.c"; 
 9 char newpathnot[] = "./gong/suo.c"; 
10 extern int errno; 
11 
12 if( rename(path,newpathnot) == 0) 
13 { 
14 printf("the file %s was moved to %s.",path,newpathnot); 
15 } 
16 else 
17 { 
18 printf("Can't move the file %s.
",path); 
19 printf("errno:%d
",errno); 
20 printf("ERR:%s
",strerror(errno)); 
21 perror("Err"); 
22 } 
23 
24 if(rename(path,newpath) == 0) 
25 printf("the file %s was moved to %s.
",path,newpath); 
26 else 
27 { 
28 printf("Can't move the file %s.
",path); 
29 printf("errno:%d
",errno); 
30 printf("ERR:%s
",strerror(errno)); 
31 } 
32 return 0; 
33 } 
34 
35 
36 gcc rename.c -o rename 
37 ./rename 
38 
39 Can't move the file ./first.c. 
40 errno:2 
41 ERR:No such file or directory 
42 Err: No such file or directory 
43 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语句!

原文地址:https://www.cnblogs.com/pencil-zh/p/4508055.html