你好,游客 登录 注册 搜索
背景:
阅读新闻

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

[日期:2010-08-18] 来源:edsionte.com  作者:edsionte [字体:大 中 小]

之前我写过一个关于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.linuxidc.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

linux
相关资讯       c编程  Linux编程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款