Read text from a file and realloc when needed

前端 未结 1 1948
执念已碎
执念已碎 2020-12-21 05:43

I want to read text from a text file line by line and do some processing on these lines. I can do all processing, but I can\'t do grow memory with malloc-realloc. I gave lim

1条回答
  •  庸人自扰
    2020-12-21 05:54

    fgets(linebuffer,maxlinelen,fp)
    

    reads and stores at most maxlinelen - 1 characters in linebuffer and 0-terminates it. Thus

    if(strlen(linebuffer)==maxlinelen)
    

    is never satisfied, strlen(linebuffer) can be at most maxlinelen - 1. Change the condition, and you will see that maxlinelen increases if the file contains long lines (unless realloc fails).

    Your current code will however count the partial line read in as an entire line then, and read the next chunk of the line as a new line. To grow the buffer until the entire line fits in, you must continue reading from the file before collecting the line length and incrementing the line count. But we must check whether a full line (including the newline at the end) was read in case fgets reads the maximal allowed number of chars before enlarging the buffer, or we'd concatenate the following line and count two (or in freak cases even more) lines as one.

    while((fgets(linebuffer,maxlinelen,fp))!=NULL)
      {
      while((strlen(linebuffer) == maxlinelen-1) && (linebuffer[maxlinelen-2] != '\n'))
      {
        maxlinelen*=2;
        linebuffer=realloc(linebuffer,maxlinelen * sizeof(char));
        if(linebuffer==NULL)
        {
            printf("Error occurred reallocating space for linebuffer");
            exit(1);
        }
        fgets(linebuffer + (maxlinelen/2 - 1), maxlinelen/2 + 1, fp);
      }
    

    would be a (rather inefficient, due to the strlen calls) way to do that.

    0 讨论(0)
提交回复
热议问题