错误输出函数perror和strerror用法

头文件

  #include< stdio.h>  

注意

  不可以掉了这个头文件,perror是包含在 stdio.h这个文件里的//

定义函数

  void perror(const char *s);     例如:perror ("open_port");

        char* strerror(interrnum);


函数说明

  perror ( )用 来 将 上 一 个 函 数 发 生 错 误 的 原 因 输 出 到 标 准 设备 (stderr) 。参数 s 所指的字符串会先打印出,后面再加上错误原因字符串。此错误原因依照全局变量error 的值来决定要输出的字符串。  在库函数中有个error变量,每个error值对应着以字符串表示的错误类型。当你调用"某些"函数出错时,该函数已经重新设置了error的值。perror函数只是将你输入的一些信息和现在的error所对应的错误一起输出。

        strerror( )通过标准错误的标号,获得错误的描述字符串 ,将单纯的错误标号转为字符串描述,方便用户查找错误。

        perror和strerror都是C语言提供的库函数,用于获取与erno相关的错误信息,区别不大,用法也简单。最大的区别在于perror向stderr输出结果,而 strerror向stdout输出结果。

测试用例

test.c文件
 
    #include <stdio.h>  
    #include <string.h>  
    #include <errno.h>  
      
    int main(int argc, char* argv[])  
    {  
        FILE *fp;  
        if ((fp = fopen(argv[1], "r")) == NULL)  
        {  
            perror("perror:");  
            printf("strerror:%s\n", strerror(errno));  
        }  
        return 0;  
    } 

运行结果:

root@ubuntu:/nfsroot/exercise# gcc test.c -o test
root@ubuntu:/nfsroot/exercise#
root@ubuntu:/nfsroot/exercise# ls
led  led.c  led.c~  test  test.c  test.c~
root@ubuntu:/nfsroot/exercise#
root@ubuntu:/nfsroot/exercise#
root@ubuntu:/nfsroot/exercise# ./test
perror:: Bad address
strerror:Bad address

root@ubuntu:/nfsroot/exercise# ./test nofile
perror:: No such file or directory
strerror:No such file or directory

root@ubuntu:/nfsroot/exercise#







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值