Linux下把错误捕获函数放入error.h


之前我写过一个关于Linux下C编程中错误捕获函数的文章,即我们可以自己编写一个函数来捕获一些错误,让程序员处理错误的时候更简单。如果将这个函数放入error.h头文件中,那么以后就可以直接调用了。本文便是和大家一起讨论如何将自己编写的错误捕获函数放入头文件error.h中。

头文件放在/usr/include目录下,进入这个目录,然后用vi编辑器打开error.h文件。要添加的两个函数如下:

void my_err1(int error)
{
 printf("error:  %s with errno: %d\n",strerror(error),error);
 exit(1);
}
void my_err2(const char* err_string,int line,int error)
{
 printf("error:  line:%d %s():%s with errno:%d\n",line,err_string,strerror(error),error);
        exit(1);
}

将上述两函数添加至文件末尾。由于strerror()函数涉及到头文件string.h,所以在已打开的error.h文件中还得添加string.h头文件。具体添加位置可参考下面:

20 #ifndef _ERROR_H
21 #define _ERROR_H 1
22
23 #include "features.h"
24
25 //personal addition
26 #include "string.h"
27 //personal addition end
28
29 __BEGIN_DECLS
30

59 //personal addition
60 //brief function
61 void my_err1(int error)
62 {
63                 printf("error:  %s with errno: %d\n",strerror(error),error);
64                 exit(1);
65 }
66
67 //detailed function
68 void my_err2(const char* err_string,int line,int error)
69 {
70                 printf("error:  line:%d %s():%s with errno:%d\n",line,err_string,strerror(error),error);
71                 exit(1);
72 }
73 //persoanl addition end
74 __END_DECLS
75
76 #endif /* error.h */

其中my_err1和my_err2显示的错误信息稍有不同。添加好后就可以保存了。www.bkjia.com但是现在问题来了:按照平时我们的保存方法:wq保存时,会提示:E45: 已设定选项 ‘readonly’ (请加 ! 强制执行)。这是因为头文件属于系统文件,linux为了安全起见,不允许普通用户对其进行修改。我们可以用ls -l查看其属性:

edsionte@edsionte-laptop:/usr/include$ ls -l error.h
-rw-r--r-- 1 root root 2557 2010-06-23 12:11 error.h

  • 1
  • 2
  • 下一页

相关内容