首页 > 其他 > 详细

exit函数的妙用

时间:2014-11-10 01:11:10      阅读:292      评论:0      收藏:0      [点我收藏+]

写了一个程序,用来判断一个文件是否存在:

#include<stdio.h>
main()
{
 FILE *fp;
 fp = fopen ("/home/wang/my/ct2.c", "r+");
 if (fp == NULL)
 {
 printf("there is not this file!\n");
 }
 else
 printf("the file is exist!\n");
 fclose (fp);
 }

r+表示为读写打开一个文本文件

如果在/home/wang/my/目录下的ct2.c文档存在,

则程序运行结果为:

the file is exist!

运行结果是正确的

如果在/home/wang/my/目录下的ct2.c文档不存在,

则程序运行结果为:

there is not this file!
Segmentation fault (core dumped)

运行结果是错误的

这时需要用到exit函数,将程序修改为如下形式:

#include<stdio.h>
main()
{
 FILE *fp;
 fp = fopen ("/home/wang/my/ct2.c", "r+");
 if (fp == NULL)
 {
 printf("there is not this file!\n");
 exit(0);
 }
 else
 printf("the file is exist!\n");
 fclose (fp);
 }

程序运行结果为:

there is not this file!

运行结果是正确的!结果中没有了"Segmentation fault (core dumped)"!

exit函数的作用是关闭所有文件,终止正在执行的程序,待用户检查出错误,

修改后再运行。




exit函数的妙用

原文:http://blog.csdn.net/wangjiaweiwei/article/details/40961301

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!