Chinaunix首页 | 论坛 | 博客
  • 博客访问: 116146
  • 博文数量: 29
  • 博客积分: 1215
  • 博客等级: 中尉
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-05 16:29
文章分类
文章存档

2010年(29)

我的朋友

分类: C/C++

2010-12-07 14:35:53

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

       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

       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

       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
阅读(1103) | 评论(1) | 转发(2) |
给主人留下些什么吧!~~

chinaunix网友2010-12-08 15:12:15

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com