分享

Linux/Unix C编程之的perror函数,strerror函数,errno

 WUCANADA 2012-01-17
Linux/Unix C编程之的perror函数,strerror函数,errno
2009-07-10 17:20

#include <stdio.h> // void perror(const char *msg);

#include <string.h> // char *strerror(int errnum);

#include <errno.h> //errno

errno是错误代码,在errno.h头文件中

void perror(const char *s)

perror是错误输出函数,在标准输出设备上输出一个错误信息。

参数s一般是参数错误的函数

例如perror("fun"),其输出为:fun:后面跟着错误信息(加上一个换行符)

char *strerror(int errnum);通过参数errnum(也就是errno),返回错误信息

以下是测试程序:

//程序名:errtest.c,环境为linux

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc,char *argv[]){
FILE *fp;
char *buf;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("perror");
printf("sterror:%s\n",strerror(errno));
exit(1);
}
perror("perror");
errno=13;
printf("strerror:%s\n",strerror(errno));
fclose(fp);
return 0;
}

==============================

编译为errtest

如果输入这样的命令格式:./errtest 111.c(其中111.c不存在)

输出为:

perror: No such file or directory
sterror:Illegal seek

就是两个都是输出到屏幕上来了。而且sterror函数通过errno得到错误代码

如果命令格式为:./errtest 111.c > out.c(其中111.c不存在)

把输出重定位到out.c文件中,会发现屏幕输出为:

perror: No such file or directory
就是说函数perror始终输出到标准输出设备上。而printf输出到文件中了

如果命令格式为:./errtest 222.c(其中222.c存在)

屏幕输出为:

perror: Success
strerror: Permission denied(通过errno=12得到的一个信息)

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多