简体   繁体   English

从文件中逐个字符读取并将每一行放入一个字符串中

[英]Read character by character from a file and put each line in a String

I've to read character by character from a file and put each line in a String.我必须从文件中逐个字符地读取并将每一行放入一个字符串中。 The problem is that i don't know the size of each line so eventually I've to reallocate the memory.问题是我不知道每一行的大小,所以最终我必须重新分配内存。 So If I try a reallocation my program return error.所以如果我尝试重新分配我的程序返回错误。 Am I doing something wrong?难道我做错了什么?

    FILE * file = fopen(input,"r");
    if(file != NULL){
        char temp;
        char * line;
        line =  (char *) malloc(sizeof(char) * 10);
        int i = 0;
        while((temp = fgetc(file)) != EOF){

            if(temp == '\n'){

                i = 0;
            }
            else{
                if(i > strlen(line) - 2){
                    line = (char *) realloc(line,sizeof(line) * 10);
                }
                line[i] = (char) temp;
                i++;
            }

        }
        free(line);
        fclose(file);
    }
    else{

    }


the following proposed code:以下建议代码:

  1. cleanly compiles干净地编译
  2. performs the desired functionality执行所需的功能
  3. properly checks for errors正确检查错误
  4. outputs user error messages to stderr将用户错误消息输出到stderr
  5. outputs the text reason the system thinks an error occurred to stderr输出系统认为stderr发生错误的文本原因
  6. documents why each header file is included记录为什么包含每个头文件
  7. shows an example of how to handle the case where the user failed to enter a command line parameter (in this case a input file name)显示了如何处理用户未能输入命令行参数(在本例中为输入文件名)的情况的示例
  8. makes use of size_t rather than int when passing parameters to malloc() and realloc()将参数传递给malloc()realloc()时使用size_t而不是int

and now, the proposed code:现在,建议的代码:

#include <stdio.h>   // fopen(), perror(), fclose() fprintf()
#include <stdlib.h>  // exit(), EXIT_FAILURE, malloc(), realloc(). free()


int main( int argc, char *argv[] )
{
    if( argc != 2 )
    {
        fprintf( stderr, "USAGE: %s <fileName>\n", argv[0] );
        exit( EXIT_FAILURE );
    }


    FILE * file = fopen( argv[1], "r" );
    if( !file )
    {
        perror( "fopen failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    int ch;
    char * line =  malloc( 10 );
    if( !line )
    {
        perror( "malloc failed" );
        fclose( file );   // cleanup
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    size_t lineLen = 10;
    size_t i = 0;
    while( (ch = fgetc(file)) != EOF )
    {
        if( ch == '\n' )
        {
            line[i] = '\0';
            // do something with contents of line
            i = 0;
        }

        else
        {
            if(i >= lineLen )
            {
                lineLen *= 2;
                char * temp = realloc( line, lineLen );
                if( !temp )
                {
                    perror( "realloc failed" );
                    // cleanup
                    fclose( file );
                    free( line );
                    exit( EXIT_FAILURE );
                }
                line = temp;
            }
            line[i] = (char)ch;
            i++;
        }

    }
    free(line);
    fclose(file);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM