1 perror
perror函数是用来打印错误提示信息的,原型是:
#include <stdio.h>
void perror(const char *s);
它先打印s指向的字符串,然后输出当前errno值所对应的错误提示信息,例如当前errno若为12,调用perror(“ABC”),会输出"ABC: Cannot allocate memory"。
测试程序:
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int fd = 10;
int ret;
ret = close(fd);
if(ret == -1)
perror("close error");
return 0;
}
上述代码会输出:close error : Bad file descriptor
2 strerror
strerror返回errnum的值所对应的错误提示信息,例如errnum等于12的话,它就会返回"Cannot allocate memory"。
函数原型:
#include <string.h>
char *strerror(int errnum);
测试程序:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
int main(void)
{
int fd = 10;
int ret;
ret = close(fd);
if(ret == -1)
fprintf(stderr, "close error with msg is: %s\n",strerror(errno));
return 0;
}
输出信息:close error with msg is : Bad file descriptor