美文网首页
7.错误处理

7.错误处理

作者: 陈忠俊 | 来源:发表于2020-03-15 17:46 被阅读0次

C语言中的错误处理可以通过以下函数和全局变量去跟踪

  1. errno
    系统预定义的全局变量,在库函数出错的时候,可以设置errno的值。然后根据其值找到对应描述符的信息
  2. strerror(3)
#include<string.h>
char *strerror(int errnum)

功能:返回错误编号对应的描述错误的字符串
找不到错误的编号,返回“unknown error nnn”的首地址
找到错误编号,返回描述错误的字符串的首地址

  1. perror
#include<stdio.h>
void perror(const chart *s);

功能:输出最近一次函数调用的错误信息,s是用户自定义字符串。该函数没有返回值

练习一:

#include<stdio.h>
#include<string.h>
#include<errno.h>

int main(int argc, char *argv[]){
        FILE *fp = fopen(argv[1], "r");
        if(fp == NULL){
                printf("fopen failed: %s\n", strerror(errno));
                return -1;
        }
        printf("fopen success.\n");
        fclose(fp);
        return 0;
}

测试:

zhongjun@eclipse:~/linkTest$ gcc error_test.c -o hell
zhongjun@eclipse:~/linkTest$ touch aa
zhongjun@eclipse:~/linkTest$ ls -l aa
-rw-rw-r-- 1 zhongjun zhongjun 0 3  15 16:34 aa
zhongjun@eclipse:~/linkTest$ chmod 222 aa
zhongjun@eclipse:~/linkTest$ ./hell aa
fopen failed: Permission denied
zhongjun@eclipse:~/linkTest$ ls -l aa
--w--w--w- 1 zhongjun zhongjun 0 3  15 16:34 aa

aa文件没有读权限。

测试2:

#include<stdio.h>

int main(int argc, char *argv[]){
        FILE *fp = fopen(argv[1], "r");
        if(fp == NULL){
                perror("fopen: ");
                return -1;
        }
        printf("fopen success.\n");
        fclose(fp);
        return 0;
}

输出:

zhongjun@eclipse:~/linkTest$ gcc error_test.c -o hell2
zhongjun@eclipse:~/linkTest$ ./hell2 aa
fopen: : Permission denied

宏定义方法:

//s_stdio.h
#ifndef S_STDIO_H_
#define S_STDIO_H_
#define E_MSG(STR, VAL) do{perror(STR); return (VAL);}while(0)
#endif
#include<stdio.h>
#include"s_stdio.h"

int main(int argc, char *argv[]){
        FILE *fp = fopen(argv[1], "r");
        if(fp == NULL){
                E_MSG("fopen", -1);
        }
        printf("fopen success.\n");
        fclose(fp);
        return 0;
}

输出:

zhongjun@eclipse:~/linkTest$ gcc error_test.c -o hell3
zhongjun@eclipse:~/linkTest$ ./hell3 aa
fopen: Permission denied

相关文章

网友评论

      本文标题:7.错误处理

      本文链接:https://www.haomeiwen.com/subject/idosehtx.html