C++ errno

一、 errno 介绍

  • errno 是一个全局的宏;
  • 程序执行的时候会把 errno 置上对应的错误码,同时也有一些相关的宏,如下:
#define errno   (*_errno())
#define _doserrno   (*__doserrno())
#define _sys_errlist (__sys_errlist())
#define _sys_nerr (*__sys_nerr())
  • 程序开始执行的时候,errno 和 _doserrno 会被置 0,当一个系统调用出错时,errno 会被置上一个非 0 的值;因为 errno 存储了上一次调用的值,所以它可能会被成功的调用改变,所以一旦出错,需要里面把这个值输出来;
  • I/O 操作发生错误时,_doserrno 会被置上;

二、错误信息输出

  • errno 是一个数字,具体含义对应在 _sys_errlist 中,比如发生错误时,可以输出 _sys_errlist [ errno ] 来看具体含义,_sys_nerr 则代表了 _sys_errlist 这个数组的长度;
  • 为了安全性考虑,一般可以采用 perror、strerror 或 strerror_s 来进行错误码的输出;
	FILE* pf = fopen("test.txt", "r");
	if (!pf) {
    
    
		perror("perror");
		printf("strerror: %s\n", strerror(errno));
		printf( _strerror("_strerror") );
	}
perror: No such file or directory
strerror: No such file or directory
_strerror: No such file or directory

三、错误码表查询

错误码 含义
NULL 0 No error
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
ESRCH 3 No such process
EINTR 4 Interrupted function call
EIO 5 Input/output error
ENXIO 6 No such device or address
E2BIG 7 Arg list too long
ENOEXEC 8 Exec format error
EBADF 9 Bad file descriptor
ECHILD 10 No child processes
EAGAIN 11 Resource temporarily unavailable
ENOMEM 12 Not enough space
EACCES 13 Permission denied
EFAULT 14 Bad address
/ 15 Unknown error
EBUSY 16 Resource device
EEXIST 17 File exists
EXDEV 18 Improper link
ENODEV 19 No such device
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENFILE 23 Too many open files in system
EMFILE 24 Too many open files
ENOTTY 25 Inappropriate I/O control operation
/ 26 Unknown error
EFBIG 27 File too large
ENOSPC 28 No space left on device
ESPIPE 29 Invalid seek
EROFS 30 Read-only file system
MLINK 31 Too many links
EPIPE 32 Broken pipe
EDOM 33 Domain error
ERANGE 34 Result too large
/ 35 Unknown error
EDEADLK 36 Resource deadlock avoided
/ 37 Unknown error
ENAMETOOLONG 38 Filename too long
ENOLCK 39 No locks available
ENOSYS 40 Function not implemented
ENOTEMPTY 41 Directory not empty
EILSEQ 42 Illegal byte sequence

猜你喜欢

转载自blog.csdn.net/WhereIsHeroFrom/article/details/108919384