您的位置:首页 > 编程语言 > C语言/C++

[收藏]C++ Tips(5)--返回值的检查

2005-11-08 00:00 246 查看
[收藏]C++ Tips(5)--返回值的检查
document.title="[收藏]C++ Tips(5)--返回值的检查 - "+document.title
/*这一系列文章《C++ Tips》是公司Code Committee专家会推荐工程师看的,感觉很好,拿出来与大家共同提高。并不是知道多少会使人与人产生差别,真正的差别在于你能做到多少。--coofucoo*/对系统调用的返回值进行判断
继续上一条,对于一些系统调用,比如打开文件,经常有这种情况,许多程序员对fopen返回的指针不做任何判断,就直接使用了。然后发现文件的内容怎么也读出不,或是怎么也写不进去。还是判断一下吧:
fp = fopen("log.txt", "a");
if ( fp == NULL ){
printf("Error: open file error/n");
return FALSE;
}
其它还有许多,比如:socket返回的socket号,malloc返回的内存等等。我的建议是:只要是函数声明时返回值不是void类型,就请对这些系统调用返回的东东进行判断,举一个最常见的函数:close,它是这么定义的:
int close(int fd);
再看一下它的一些描述:“Not checking the return value of close is a common but nevertheless serious programming error. It is quite possible that errors on a previous write operation are first reported at the final close. Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and disk quotas.”因为现代的操作系统都启用了延时写技术,在你调用write之后并不一定马上就将数据写入磁盘,所以close的时候有可能此时系统真正向磁盘写入大段数据导致close失败。而你缺认为文件已被关闭。解决的方法是判断close的返回值,失败后稍等一会儿,或是使用其他策略。

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=480990
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: