//_55_打开和关闭文件
//_55_main.cpp
//fopen(),fclose()
#include <stdio.h>
#include <stdlib.h>
int main()
{
//定义一个文件指针
FILE *fp;
char ch,filename[10];
printf("Please input the name of file:");
scanf("%s",filename);//输入字符串并赋给变量filename
//以读的使用方式打开文件filename
//如果文件打开不成功,则调出整个程序,如果打开成功,再将文件关闭
if((fp=fopen(filename,"r"))==NULL)
{
printf("Can not open the file.\n");
exit(0);//正常跳出程序
}
//关闭文件
fclose(fp);
system("pause");
return 0;
}55_打开和关闭文件
本文介绍了一个简单的C语言程序示例,演示了如何使用fopen()和fclose()函数来打开和关闭文件。程序首先提示用户输入文件名,然后尝试以只读模式打开该文件,并在打开失败时给出提示并退出程序。最后,程序会确保已打开的文件被正确关闭。

被折叠的 条评论
为什么被折叠?



