• 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;
    }

    /* 输出:

    */ 

     

  • 相关阅读:
    【lambda表达式】Comparator接口
    SpringBoot
    金融和大模型的“两层皮”问题
    Android移动应用开发之Button按钮与事件
    C++作业2:类与类关系设计
    答辩步骤及相关准备1
    统计学习导论(ISLR) 第六章变量选择课后习题
    Android在XML和代码中,同时设置背景,导致背景叠加的问题
    Qt实现将字节数组以hex形式显示到文本框的方法
    AJAX 请求
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/125631727