C语言 文件读写 ferror 函数

ChatGPT 3.5 国内中文镜像站免费使用啦

零基础 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 file\n");
    else
        printf("No error in reading\n");
 
    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

ChatGPT 3.5 国内中文镜像站免费使用啦
© 版权声明
THE END
喜欢就支持一下吧
点赞1 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容