当前位置 博文首页 > dangzhangjing97的博客:fopen函数的详解与fclose函数的详解

    dangzhangjing97的博客:fopen函数的详解与fclose函数的详解

    作者:[db:作者] 时间:2021-08-09 22:23

    fopen()

    功能:打开一个特定的文件,并把一个流和这个文件相关联
    头文件:#include<stdio.h>
    

    原型:

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

    参数说明:
    path:是一个字符串,包含欲打开的文件路径及文件名
    mode:mode字符串则代表着流形态
       r->读,该文件必须存在;
       w->打开只写文件,若文件存在则长度清为0,
          即该文件内容消失,若不存在则创建该文件
       r+->以读/写方式打开文件,该文件必须存在
       w+->打开可读/写文件

    返回值:

    成功:它返回一个指向FILE结构的指针,该结构代表这个新创建的流
        (文件顺利打开后,指向该流的文件指针就会被返回)
    失败:它就会返回一个空指针,errno会提示问题的性质
        (如果文件打开失败,则返回NULL,并把错误代码存在errno中)
    

    ps:应始终检查fopen函数的返回值

    例子:

    FILE*input;
    input = fopen("data3", "r");
    if (NULL == input)
    {
        perror("data3");
        exit(EXIT_FAILURE);
    }
    

    fclose()

    功能:关闭一个流
    头文件:#include<stdio.h>
    原型:int fclose(FILE*f);
    返回值:对于输出流,fclose函数会在文件关闭前刷新缓冲区,
           如果它执行成功,fclose返回零值
    

    注意:使用fclose函数就可以把缓冲区内最后剩余的数据输出到内核缓冲区,并释放文件指针和有关的缓冲区

    1.
    代码:

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<unistd.h>//exit函数的头文件
    int main()
    {
      FILE*fp=fopen("myfile","w+");
      if(NULL==fp)
      {
        perror("fopen");
        exit(1);
      }
      const char*msg="hello\n";
      int count = 5;
      while(count--)
      {
        fwrite(msg,1,strlen(msg),fp);
      }
    
      fclose(fp);//fopen之后记得fclose
      return 0;
    }

    运行结果:

    这里写图片描述

    2.

    #include<stdlib.h>
    #include<unistd.h>
    int main()
    {
     FILE*fp=fopen("myfile","r");
     if(NULL==fp)
     {
      perror("fopen");
      exit(1);
     }
     const char*msg="hello\n";
     char buf[10]={0};
     ssize_t s= fread(buf,strlen(msg),1,fp);
     printf("buf:%s\n",buf);
     fclose(fp);
     return 0;
    }
    

    运行结果:

    这里写图片描述

    cs
    下一篇:没有了