C语言编程,函数返回值判断!

2340阅读 0评论2010-04-07 chinaltang
分类:C/C++

要养成良好的编程习惯,特别是使用一些设计到I/O操作的系统API(fopen,open,socket,bind,stat,opendir)进行编程时一定要对函数的执行结果状态进行判断。否则,当程序规模较大时,如果出现问题将很难进行定位。

简单如:

打开一个目录,并读取目录下一个文件的状态信息时,应如下编写代码

DIR *dp = NULL;
struct dirent  *dirEntry = NULL;
struct stat dirStat;

if((dp = opendir(dirName)) == NULL)
{
perror("opendir");
exit(1);
}

if((dirEntry = readdir(dp)) == NULL)
{
perror("readdir");
exit(2);
}

if(stat(dirEntry->d_name,&dirStat) < 0)
{
perror("stat");
exit(3);
}
上一篇:UDP的不可靠性
下一篇:Workbench 中使用 Simulator 的注意事项