- 6
- 0
- 约1.45千字
- 约 2页
- 2023-05-08 发布于上海
- 举报
错误处理—— stderr和exit
cat 程序的错误处理功能并不完善。问题在于,如果因为某种原因而造成其中的一个文 件无法访问,相应的诊断信息要在该连接的输出的末尾才能打印出来。当输出到屏幕时,这种处理方法尚可以接受,但如果输出到一个文件或通过管道输出到另一个程序时,就无法接受了。
为了更好地处理这种情况,另一个输出流以与stdin和stdout相同的方式分派给程序, 即stderr。即使对标准输出进行了重定向,写到stderr中的输出通常也会显示在屏幕上。下面我们改写cat程序,将其出错信息写到标准错误文件上。
#include stdio.h
/* cat: concatenate files, version 2 */ main(int argc, char *argv[])
{
FILE *fp;
void filecopy(FILE *, FILE *);
char *prog = argv[0]; /* program name for errors */ if (argc == 1 ) /* no args; copy standard input */ filecopy(stdin, stdout);
else
while (--argc 0)
if ((fp = fopen(*++argv, r)) == NULL) { fprintf(stderr
原创力文档

文档评论(0)