C语言的文件操作———fopen(打开文件)
tips:
- function —— open the file and show the message on the screen (if this file not exists,program will thorws a exception)
- program as follows:
//c语言打开文件
#include<stdio.h>
#include<stdlib.h>
#define MAXN 1024
//1.文件源字符串
//2.fopen打开 (打开的方式("r"wa(t、b)))
//3.循环输出文件的内容
//4.关闭文件指针
int main(){
//定义所需的变量
FILE *fp;
char content[MAXN+1];
char *source="test.txt";
//打开文件 文件必须存在,不存在出错
if((fp=fopen(source,"rt"))==NULL){
puts("打开文件失败!");
exit(0);//异常退出
}
//输出文件中的内容
while(fgets(content,MAXN,fp)!=NULL){//缓冲器中读入的有内容
printf("%s",content);
}
//关闭文件指针
fclose(fp);
return 0;
}
本文详细介绍了使用C语言进行文件操作的方法,特别是如何利用fopen函数打开文件,并展示了如何读取文件内容到内存中并显示在屏幕上。如果指定的文件不存在,程序将抛出异常并终止。
82

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



