• C和指针 第15章 输入/输出函数 15.14 流错误函数


    15.14 流错误函数
        下面的函数用于判断流的状态:
        int feof( FILE *stream );
        int ferror( FILE *stream );
        void clearerr( FILE *stream );
        如果流当前处于文件尾,feof函数返回真。这个状态可以通过对流执行fseek、rewind或fsetpos函数来清除。ferror函数报告流的错误状态,如果出现任何读/写错误,函数就返回真。最后,clearerr函数对指定流的错误标志进行重置。

    /*
    ** 流错误函数。 
    */
    #include <stdio.h>
    #include <stdlib.h>

    int main( void ){
        FILE *input;
        int result;
        
        input = fopen( "no_existence.txt", "r" );
        if( !input ){
            printf( "fail to open no_existence.txt file.\n" );
            perror( "no_existence.txt:" );
            result = ferror( input );
            printf( "the result of ferror( input ) is %d\n", result );
            clearerr( input );
            printf( "after clearerr( input ), result is %d\n", result );
            input = fopen( "no_existence.txt", "w" );
            if( !input ){
                printf( "fail to create the no_existence.txt file.\n" );
                perror( "no_existence.txt:" );
                exit( EXIT_FAILURE );
            } else{
                printf( "succeed to create the no_existence.txt file.\n" );
                fprintf( input, "%s %d %c\n", "xiao hong", 25, 'f' );
                fprintf( input, "%s %d %c\n", "xiao shu", 26, 'm' );
                fprintf( input, "%s %d %c\n", "xiao ming", 20, 'f' );
                input = freopen( "no_existence.txt", "r", input ); 
                if( !input ){
                    printf( "fail to open no_existence.txt file.\n" );
                    perror( "no_existence.txt:" );
                    exit( EXIT_FAILURE );
                } 
            }
        }
        int ch;
        while( (ch = fgetc( input )) && !feof( input ) ){
            fputc( ch, stdout );
        }
        
        return EXIT_SUCCESS;
    }

    /* 输出:

    */ 

     

  • 相关阅读:
    某商业银行核心存储选型实践经验
    八股乱背,力扣不会!下辈子远离计算机
    金融业需要的大模型,是一个系统化工程
    【图论】Floyd
    WordPress实时搜索插件Ajax Search Lite,轻松替代默认搜索功能
    亚马逊云科技re:Invent 2022 Ruba Borno主题演讲
    分布式微服务架构下网络通信的底层实现原理
    HTML经典布局方式
    Linux C 应用搜索动态库
    项目管理,看这篇就够了,但一定要实操!
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/125631727