免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 694 | 回复: 0
打印 上一主题 下一主题

出错处理 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-05-10 08:44 |只看该作者 |倒序浏览

               
               
                出错处理
assert() 函数用法
assert宏的原型定义在中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:
#include
void assert( int expression );
assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,
然后通过调用 abort 来终止程序运行。
请看下面的程序清单badptr.c:
#include iostream.h>
#include assert.h>  //assert(expression) need
int main( void )
{
       FILE *fp;
   
       fp = fopen( "test.txt", "w" );//以可写的方式打开一个文件,如果不存在就创建一个同名文件
       assert( fp );                          //所以这里不会出错  assert() 里的参数也可以是表达式
       fclose( fp );
   
       fp = fopen( "noexitfile.txt", "r" );//以只读的方式打开一个文件,如果不存在就打开文件失败
       assert( fp );                           //所以这里出错
       fclose( fp );                           //程序永远都执行不到这里来
       return 0;
}
[root@localhost error_process]# g++ badptr.c -o badptr
[root@localhost error_process]# ./badptr
a.out: badptr.c:13: main: Assertion `fp' failed.
已放弃
使用assert的缺点是,频繁的调用会极大的影响程序的性能,增加额外的开销。
在调试结束后,可以通过在包含#include 的语句之前插入 #define NDEBUG 来禁用assert调用,示例代码如下:
#include
#define NDEBUG
#include
用法总结与注意事项:
1)在函数开始处检验传入参数的合法性
如:
int resetBufferSize(int nNewSize)
{
//功能:改变缓冲区大小,
//参数:nNewSize 缓冲区新长度
//返回值:缓冲区当前长度
//说明:保持原信息内容不变     nNewSize= 0);
assert(nNewSize =0 && nOffset+nSize= 0);
assert(nOffset+nSize
Description
The  header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong. Its value is significant only when the call returned an error (usually -1), and a function that does succeed is allowed to change errno.
such as:
#include
#include   //sqrt()
#include   //errno and perror need
int main()
{
double d;
d=sqrt((double)-1);
if(errno)
{
perror("sqrt -1 failed");
errno=0;
}
else
cout
void perror(const char *s)
exit()
好多的参考书都需要头文件#include ,但是我在运行c++程序时,跟本就不需要这个头文件
void exit(int status);
strip
用strip命令处理一个程序意味着用strip命令去除编译好的中的符号,这些符号通常是调试符号。这样做减少了程序对磁盘和内存的占用量,但不好的副作用是让调试变得困难
系统日志函数
头文件定义了到syslogd的接口,要创建一个日志消息,可使用syslog函数,其原型为
#include
void syslog(int priority, char *format, ....)
format指定写入日志的消息和任何类亿printf的格式说明字符串。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/45689/showart_683000.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP