目录

零基础 C/C++ 学习路线推荐 : C/C++ 学习目录 >> C 语言基础入门

一.ferror 函数简介

C 语言 ferror 函数用于检测文件读写过程中是否有产生错误,声明如下:

#include <stdio.h>

/*
*描述:写入数据到缓冲区文件
*
*参数:
*   [in]  stream:文件指针句柄
*
*返回值:对文件读写时出错时,文件就会产生错误标志!如果出现读写错误,返回非 0 值,如果没有读写错误,返回 0
*/

int ferror(FILE *stream);

应该注意,对同一个文件(文件指针或文件描述符)每一次调用读 fread /写 fwrite 等操作函数,均产生一个新的 ferror 函数值,因此,应当在调用读 fread /写 fwrite 等函数后立即检查 ferror 函数的值,否则信息会丢失。

二.ferror 函数实战

/******************************************************************************************/
//@Author:猿说编程
//@Blog(个人博客地址): www.codersrc.com
//@File:C语言教程 - C语言 文件读写 ferror 函数
//@Time:2021/07/22 07:30
//@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!
/******************************************************************************************/

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *f;
    char str[100];

    //Check the existence of that file
    if((f=fopen("includehelp.txt","r"))==NULL){
        printf("Cannot open the file...");
        //if not exist program is terminated
        exit(1);
    }

    // Check if here is some error in the file
    if(ferror(f))
        printf("Error to read the filen");
    else
        printf("No error in readingn");

    printf("File content is--n");
    //print the strings until EOF is encountered
    while(!feof(f)){
        fgets(str,100,f);
        //print the string
        printf("%s",str);
    }

    //close the opened file
    fclose(f);

    return 0;
}

应该注意,对同一个文件(文件指针或文件描述符)每一次调用读 fread /写 fwrite 等操作函数,均产生一个新的 ferror 函数值,因此,应当在调用读 fread /写 fwrite 等函数后立即检查 ferror 函数的值,否则信息会丢失。

三.猜你喜欢

  1. C 语言 数组下标越界和内存溢出区别
  2. C 语言 使用指针遍历数组
  3. C 语言 指针和数组区别
  4. C 语言 指针数组和数组指针区别
  5. C 语言 野指针
  6. C 语言 函数值传递和址传递
  7. C 语言 函数不定长参数
  8. C 语言 函数指针
  9. C 语言 指针函数
  10. C 语言 回调函数 callback
  11. C 语言 #pragma once
  12. C 语言 #include <> 与 #include “” 区别
  13. C 语言 const 修饰函数参数
  14. C 语言 const 和 define 区别
  15. C 语言 #运算符
  16. C 语言 ##运算符
  17. C 语言 __VA_ARGS__
  18. C 语言 ##__VA_ARGS__
  19. C 语言 函数不定长参数 ##__VA_ARGS__经典案例
  20. C 语言 va_start / va_end / va_arg 自定义 printf 函数
  21. C 语言 main 函数
  22. C 语言 main 函数参数 main(int argc, char *argv[])
  23. C 语言 局部变量
  24. C 语言 全局变量
  25. C 语言 全局变量和局部变量区别
  26. C 语言 static

未经允许不得转载:猿说编程 » C 语言 文件读写 ferror 函数

本文由博客 - 猿说编程 猿说编程 发布!

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/shuopython/p/15389844.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程

4093 9.8元 100元 0.98折
3538 9.8元 98元 1折