如何从文本文件中输入文本(c)

时间:2018-04-21 22:29:19

标签: c

如何在使用2D数组进行输入时使用fgets从文本文件输入文本?

main(){

    char text[1000][1000];
    FILE *fptr;
    char fname[100];
    printf("input file name:");
    scanf("%s",fname);
    fptr=fopen(fname,"w");
    if(fptr==NULL){
        printf("Error in opening file");
        exit(1);
    }
    else{
    }
}

1 个答案:

答案 0 :(得分:0)

以下提议的代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 正确检查错误
  4. 在退出前正确清理
  5. 文件哪个头文件暴露了哪些功能以及哪些#defines
  6. 现在建议的代码:

    #include <stdio.h>    // FILE, printf(), scanf(), fprintf()
                          // fopen(), fclose(), stderr, fflush()
    #include <stdlib.h>   // exit(), EXIT_FAILURE, realloc()
    #include <string.h>   // strdup()
    
    #define MAX_FILENAME_LEN 99
    #define MAX_LINE_LEN 1000
    
    int main( void )
    {
        FILE *fptr;
        char filename[ MAX_FILENAME_LEN +1 ];
    
        printf("input file name:");
        fflush( stdout );
        if( scanf( "%99s", filename ) != 1 )
        {
            fprintf( stderr, "scanf failed to read the file name\n" );
            exit( EXIT_FAILURE );
        }
    
        // implied else, scanf successful
    
        fptr = fopen( filename, "w" );
        if( !fptr )
        {
            perror( "fopen failed" );
            exit( EXIT_FAILURE );
        }
    
        // implied else, fopen successful
    
        char **savedText = NULL;
        size_t numLines = 0;
        char line[ MAX_LINE_LEN ];
    
        while( fgets( line, sizeof(line), fptr ) )
        {
            char *temp = realloc( savedText, (numLines+1)*sizeof(char*) );
            if( !temp )
            {
                perror( "realloc failed" );
                fclose( fptr );
                for( size_t i=0; i<numLines; i++ )
                {
                    free( savedText+i );
                }
                free( savedText );
                exit( EXIT_FAILURE );
            }
    
            // implied else, realloc successful
    
            *savedText = temp;
            savedText[ numLines ] = strdup( line );
            if( !savedText+numLines )
            {
                perror( "strdup failed" );
                fclose( fptr );
                for( size_t i=0; i<numLines; i++ )
                {
                    free( savedText+i );
                }
                free( savedText );
                exit( EXIT_FAILURE );
            }
    
            // implied else, strdup successful
    
            numLines++;
    
        } // end while()
    
        fclose( fptr );
        for( size_t i=0; i<numLines; i++ )
        {
            free( savedText[ i ] );
        }
        free( savedText );
        return 0;
    }