详解C语言中的错误报告errno与其相关应用方法
C语言标准库中的错误报告用法有三种形式。 #ifndef errno extern int errno; #endif 外部变量errno保存库程序中实现定义的错误码,通常被定义为errno.h中以E开头的宏, # define EDOM 33 /* Math argument out of domain of function. */ EDOM的意思是参数不在数学函数能接受的域中,稍后的例子中用到了这个宏。 在linux中使用c语言编程时,errno是个很有用的动动。他可以把最后一次调用c的方法的错误代码保留。但是如果最后一次成功的调用c的方法,errno不会改变。因此,只有在c语言函数返回值异常时,再检测errno。 一个简单的例子 #include <stdio.h> #include <errno.h> #include <string.h> #include <math.h> int main(void) { errno = 0; int s = sqrt(-1); if (errno) { printf("errno = %dn",errno); // errno = 33 perror("sqrt failed"); // sqrt failed: Numerical argument out of domain printf("error: %sn",strerror(errno)); // error: Numerical argument out of domain } return 0;
2、strerror char *strerror(int errno) 使用方式如下: fprintf(stderr,"error in CreateProcess %s,Process ID %d ",strerror(errno),processID) 将错误代码转换为字符串错误信息,可以将该字符串和其它的信息组合输出到用户界面。 void perror(const char *s) 函数说明 # if !defined _LIBC || defined _LIBC_REENTRANT /* When using threads,errno is a per-thread value. */ # define errno (*__errno_location ()) # endif # endif /* !__ASSEMBLER__ */ #endif /* _ERRNO_H */ 也就是说,在没有定义__LIBC或者定义_LIBC_REENTRANT的时候,errno是多线程/进程安全的。 #include <stdio.h> #include <errno.h> int main( void ) { #ifndef __ASSEMBLER__ printf( "Undefine __ASSEMBLER__/n" ); #else printf( "define __ASSEMBLER__/n" ); #endif #ifndef __LIBC printf( "Undefine __LIBC/n" ); #else printf( "define __LIBC/n" ); #endif #ifndef _LIBC_REENTRANT printf( "Undefine _LIBC_REENTRANT/n" ); #else printf( "define _LIBC_REENTRANT/n" ); #endif return 0; }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |