文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>例示strerror和perror

例示strerror和perror

时间:2010-12-07  来源:longmenyu

预备知识:
1.     strerror- return string describing error number 
        #include <string.h>

       char *strerror(int errnum);

       The  strerror() function returns a string describing the error code passed in the
       argument errnum, possibly using the LC_MESSAGES part of  the  current  locale  to
       select  the appropriate language.  This string must not be modified by the appli-
       cation, but may be modified by a subsequent call to perror() or  strerror().   No
       library function will modify this string.
2.NAME
       perror - print a system error message

SYNOPSIS
       #include <stdio.h>

       void perror(const char *s);
DESCRIPTION
       The  routine perror() produces a message on the standard error output, describing
       the last error encountered during a call to a system or library function.   First
       (if  s  is  not  NULL  and *s is not a null byte ('\0')) the argument string s is
       printed, followed by a colon and a blank.  Then the message and a new-line.

3.     #include <stdio.h>

       int printf(const char *format, ...);
       int fprintf(FILE *stream, const char *format, ...);
 区别:
 fprintf(stderr, "Can't open it!\n");
 fprintf(stdout, "Can't open it!\n");
 printf("Can't open it!\n");

stdout -- 标准输出设备 (printf("..") 同 stdout)
stderr -- 标准错误输出设备
两者默认向屏幕输出。
但如果用转向标准输出到磁盘文件,则可看出两者区别。stdout,printf输出到磁盘文件,stderr在屏幕。

例如:
./a.out
Can't open it!
Can't open it!
Can't open it!

转向标准输出到磁盘文件tmp.txt
 ./a.out > tmp.txt
Can't open it!    //由stderror输出

用TYPE 看 tmp.txt的内容:
TYPE tmp.txt
Can't open it!  //由stdout输出
Can't open it!  //由printf输出

下面的程序清单显示这两个出错函数的使用方法:

#include <stdio.h>
#include <errno.h>
#include <stdlib.h> //exit(0);

#include <string.h>  //strerror()

int main(int argc,char *argv[])
{
    fprintf(stderr,"EACCES:%s\n",strerror(EACCES));
    errno = ENOENT;
    perror(argv[0]);
    exit(0);

}

编译源程序:
      gcc -o error error.c
运行程序:
      ./error
执行结果:
EACCES:Permission denied
./error: No such file or directory
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载