C中需要检验其执行是否成功的函数(检验返回值)

来源:互联网 发布:100lu最新域名 编辑:程序博客网 时间:2024/06/09 15:27

一、malloc(), 因为当内存分配完了后,就无法再分配空间了,所以malloc失败也是有的是,当malloc失败时返回NULL.

char *s = (void *)malloc(SIZE);

if(s == NULL)

{

printf("malloc failed !\n");

return -1

}

二、fopen() , 因为当文件不存在,或是打开的方式不对(没有权限时),则fopen失败是很经常的,当fopen失败时返回NULL.

FILE *fp;

fp = fopen("filename","a+");

if(fp == NULL)

{

printf("the file open failed !\n");

return -1;

}

三、当使用命令行参数时,要对参数的个数进行检验

int main(int argc , char **argv)

{

if(argc < 2)

{

printf("input the argc error ! \n");

return -1;

}

}



0 0
原创粉丝点击