写了一个程序,用来判断一个文件是否存在:
#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函数的作用是关闭所有文件,终止正在执行的程序,待用户检查出错误,
修改后再运行。