如何把errno的数字转换成相应的文字说明?
方式一:可以使用strerrno函数
char
*strerror(int
errno)
使用方式如下:
fprintf(stderr,"error
in
CreateProcess
%s,
Process
ID
%d
",strerror(errno),processID)
将错误代码转换为字符串错误信息,可以将该字符串和其它的信息组合输出到用户界面。
注:假设processID是一个已经获取了的整形ID
方式二:使用perror函数
void
perror(const
char
*s)
函数说明
perror
(
)用来将上一个函数发生错误的原因输出到标准错误(stderr),参数s
所指的字符串会先打印出,后面再加上错误原因
字符串。此错误原因依照全局变量
errno
的值来决定要输出的字符串。
另外并不是所有的c函数调用发生的错误信息都会修改errno。例如gethostbyname函数。
errno是否是线程安全的?
errno是支持线程安全的,而且,一般而言,编译器会自动保证errno的安全性。
我们看下相关头文件
/usr/include/bits/errno.h
会看到如下内容:
#
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
}
一般都是在处理文件时用到的比较多,如:
#include <stdio.h>#include <stdlib.h>
int main(void)
{
perror("File error ")
}
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp
if((fp=fopen("test", "rb"))==NULL) {
printf("Cannot open file.\n")
exit(1)
}
putc('C', fp)
if(ferror(fp)) { // 检测文件是否出错
printf("File Error\n")
exit(1)
}
fclose(fp)
return 0
}