目录
一、errno、perror()、strerror(errno)
二、实例
1、errno
2、perror()
3、strerror(errno)
一、errno、perror()、strerror(errno)
- errno是一个预定义的外部整型(int)变量,通常包含在头文件中;
- 当系统调用或库函数发生错误时,它们通常会设置errno以指示发生了哪种错误;
- errno的值仅在函数失败时才会被设置,并且会覆盖之前的值;
- 通过检查errno的值,程序员可以确定发生了什么错误,并据此编写适当的错误处理代码;
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_ERRNO_BASE_H #define _ASM_GENERIC_ERRNO_BASE_H #define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Argument list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ #define ENOMEM 12 /* Out of memory */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Block device required */ #define EBUSY 16 /* Device or resource busy */ #define EEXIST 17 /* File exists */ #define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ #define EINVAL 22 /* Invalid argument */ #define ENFILE 23 /* File table overflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ETXTBSY 26 /* Text file busy */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ #define EPIPE 32 /* Broken pipe */ #define EDOM 33 /* Math argument out of domain of func */ #define ERANGE 34 /* Math result not representable */ #endif二、实例
1、errno
#include <stdio.h> #include <errno.h> int main() { FILE*fp; fp = fopen("temp","r"); if(fp == NULL) { fprintf(stderr,"fopen() failed! errno = %d\n",errno); exit(1); } puts("OK!"); exit(0); }运行结果:
fopen() failed! errno = 2errno = 2 从内核定义可以看到表示没有文件或目录
#define ENOENT 2 /* No such file or directory */直接使用errno存在一个缺陷,因为errno是一个整型数值,需要查看内核代码才能知道含义。可以使用 perror()、strerror(errno) 打印错误字符串。
2、perror()
#include <stdio.h> #include <errno.h> int main() { FILE*fp; fp = fopen("temp","r"); if(fp == NULL) { //fprintf(stderr,"fopen() failed! errno = %d\n",errno); perror("fopen() failed!"); exit(1); } puts("OK!"); exit(0); }perror()可以直接输出错误信息,输出结果如下:
fopen() failed!: No such file or directory3、strerror(errno)
strerror(errno)将errno错误号转化成错误字符串
#include <stdio.h> #include <errno.h> #include <string.h> int main() { FILE*fp; fp = fopen("temp","r"); if(fp == NULL) { //fprintf(stderr,"fopen() failed! errno = %d\n",errno); //perror("fopen() failed!"); fprintf(stderr,"fopen() failed! errno = %s\n",strerror(errno)); exit(1); } puts("OK!"); exit(0); }运行结果:
fopen() failed! errno = No such file or directory