预备知识:
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
阅读(649) | 评论(0) | 转发(0) |