• perror 与 strerror


    errno、stderr、perror函数和strerror函数

    1. errno表示错误代码。 记录系统的最后一次错误代码。代码是一个int型的值,在errno.h中定义。系统每一次出错都会对应一个出错代码,例如12表示“Cannot allocate memory"。

    2. stderr 是linux(unix)标准出错输出。linux中的一个进程启动时,都会打开三个文件:标准输入、标准输出和标准出错处理。通常这三个文件都与终端联 系。这三个文件分别对应文件描述符0、1、2。系队统自定义了三个文件指针stdin、stdout、stderr,分别指向标准输入、标准输出和标准出 错输出。通常结合fprintf使用:fprintf(stderr,"error message")。

    3. perror是错误输出函数,在标准输出设备上输出一个错误信息。是对errno的封装。例如perror("fun"),其输出为:fun:后面跟着错误信息(加一个换行符)。包含头文件stdio.h.

    4. stderror是通过参数errno,返回错误信息。即stderror(errno),可用printf函数打印出错信息,用于调试。包含头文件string.h。

    测试代码

    /*

     *时间:2012.03.11

     *功能:测试errno、perror、strerror和stderr

     *目的:验证linux下出错处理

    */

    #include <stdio.h>

    #include <stdlib.h>

    #include <errno.h>

    #include <string.h>

    int main(int argc[],char *argv[])

    {

    malloc(1);

    printf("errno = %d ",errno);

    fprintf(stderr,"stderr ");

    perror("perror");

    printf("strerror: %s ",strerror(errno));

    malloc(-1);

    printf("errno = %d ",errno);

    fprintf(stderr,"stderr ");

    perror("perror");

    printf("strerror: %s ",strerror(errno));

    return 0;

    }

    转自 : http://cunxiachunshu.lofter.com/post/17f720_4a060d

    perror和strerror的区别

    概述:

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

    测试代码如下:

    1. #include <stdio.h>  
    2. #include <string.h>  
    3. #include <errno.h>  
    4. #include <stdlib.h>
    5.   
    6. int main(int argc, char* argv[])  
    7. {  
    8.     FILE *fp;  
    9.     if ((fp = fopen(argv[1], "r")) == NULL)  
    10.     {  
    11.         perror("perror:");  
    12.         printf("strerror:%s ", strerror(errno));  
    13.     }  
    14.     exit(0);  
    15. }  


    运行结果:

    转自 : http://blog.csdn.net/lalor/article/details/7555019

  • 相关阅读:
    Kubernates集群搭建
    Spring Security——基于表达式的权限控制
    JVM常用命令参数
    Spring 注解原理
    Linux SSH免登陆配置步骤
    错误日志收集sentry的安装与简单使用
    java.lang.UnsupportedClassVersionError
    docker maven 出错:Failed to execute goal com.spotify:docker-maven-plugin:...: Request error: POST https://192.168.99.100:2376/build?t=
    redis哨兵配置主从
    spring-data-redis使用哨兵配置一主多从
  • 原文地址:https://www.cnblogs.com/IceSword-syy/p/4261885.html
Copyright © 2020-2023  润新知