文件的打开和关闭

文件的打开和关闭概念

打开就是占用资源

关闭就是释放资源

文件的打开

  1. 文件的打开函数

FILE *fopen (const char *path, const char *mode);

Path: 普通文件当前路径不需要加目录,其他要使用完整的路径

Mode:

返回值:出错返回NULL,所以使用fopen函数必须判断是否为空

  1. 文件打开的模式(非常重要)

“r” 或 “rb”

以只读方式打开文件,文件必须存在。

“r+” 或 ”r+b”

以读写方式打开文件,文件必须存在。

“w” 或 “wb”

以只写方式打开文件,若文件存在则文件长度清为0。若文件不存在则创建。

“w+” 或 “w+b”

以读写方式打开文件,其他同”w”。

“a” 或 “ab”

以只写方式打开文件,若文件不存在则创建;向文件写入的数

据被追加到文件末尾。

“a+” 或 “a+b”

以读写方式打开文件。其他同”a”

  1. 编译错误:

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 添加对应的头文件。

  1.  perror 库函数    头文件stdio.h

     strerror 库函数  头文件 errno.h  string.h

   perror和strerror 功能:打印系统的错误描述(注意:是系统错误,不是你自己代码错误)

文件的关闭:

函数原型:int fclose(FILE *stream)

  1. fclose()调用成功返回0,失败返回EOF(-1),并设置errno
  2. 流关闭时自动刷新缓冲中的数据并释放缓冲区,比如:常规文件把缓冲区内容写入磁盘
  3. 当一个程序正常终止时,所有打开的流都会被关闭
  4. fclose()函数的入参stream必须保证为非空,否则出现断错误。
#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 success\n");
       }else{
            perror("fclose");
       }
    }
    

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值