perror()与strerror()的应用及区别

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语句!

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

callinglove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值