一、文件的打开和关闭概念
打开就是占用资源
关闭就是释放资源
二、文件的打开
文件的打开函数
FILE *fopen (const char *path, const char *mode);
Path: 普通文件当前路径不需要加目录,其他要使用完整的路径
Mode:
返回值:出错返回NULL,所以使用fopen函数必须判断是否为空
文件打开的模式(非常重要)
“r” 或 “rb” | 以只读方式打开文件,文件必须存在。 |
“r+” 或 ”r+b” | 以读写方式打开文件,文件必须存在。 |
“w” 或 “wb” | 以只写方式打开文件,若文件存在则文件长度清为0。若文件不存在则创建。 |
“w+” 或 “w+b” | 以读写方式打开文件,其他同”w”。 |
“a” 或 “ab” | 以只写方式打开文件,若文件不存在则创建;向文件写入的数据被追加到文件末尾。 |
“a+” 或 “a+b” | 以读写方式打开文件。其他同”a” |
编译错误:
f_open.c:9:38: error: ‘errno’ undeclared (first use in this function)
printf("fopen:%s\n",strerror(errno));
error: ‘errno’ undeclared 表示errno变量没有定义
解决方法:如果是系统变量用include 头文件,如果是你自己的,自己手动定义。
f_open.c:10:29: warning: implicit declaration of function ‘strerror’ [-Wimplicit-function-declaration]
printf("fopen:%s\n",strerror(errno));
warning: implicit declaration of function ‘strerror’ 表示strerror函数隐示的声明
解决方法:include 添加对应的头文件。
perror 库函数 头文件stdio.h
strerror 库函数 头文件 errno.h string.h
perror和strerror 功能:打印系统的错误描述(注意:是系统错误,不是你自己代码错误)
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(int argc,char *argv[]){
FILE *fp;
int fpret;
fp = fopen("1.txt","r");
if(fp==NULL){
//printf("Open file Failed\n");
perror("fopen");
printf("fopen:%s\n",strerror(errno));
}else{
printf("Open file success\n");
// perror("open");
fpret = fclose(fp);
if(fpret==0){
printf("file close sucess\n");
}else{
perror("fclose");
}
}
三、文件的关闭
函数原型:int fclose(FILE *stream)
fclose()调用成功返回0,失败返回EOF(-1),并设置errno
流关闭时自动刷新缓冲中的数据并释放缓冲区,比如:常规文件把缓冲区内容写入磁盘
当一个程序正常终止时,所有打开的流都会被关闭
fclose()函数的入参stream必须保证为非空,否则出现段错误。
四、作业
打开一个不存在的文件,分别使用perror和strerror打印错误信息。
#include<stdio.h>
#include<errno.h>
#include<string.h>
int main(){
FILE *fp;
fp = fopen("1.txt","r+");
if(fp == NULL){
perror("fopen");
printf("fopen:%s\n",strerror(errno));
}else{
printf("fopen success\n");
}
return 0;
}
运行结果