How do I read and store string of arbitrary length using malloc and realloc in C?

后端 未结 4 1441
生来不讨喜
生来不讨喜 2021-01-22 03:53

I have a structure

typedef struct store
{
   char name[11];
    int age;
} store;

and a main function(below is part of it):

int         


        
4条回答
  •  抹茶落季
    2021-01-22 04:11

    What you need to do is read the line in smaller increments, and resize your buffer as you go.

    As an example (not tested and not meaning to be particularly elegant, just an example):

    char *readline(FILE *f)
    {
       char *buf = NULL;
       size_t bufsz = 0, len = 0;
       int keep_going = 1;
    
       while (keep_going)
       {
          int c = fgetc(f);
          if (c == EOF || c == '\n')
          {
             c = 0;             // we'll add zero terminator
             keep_going = 0;    // and terminate the loop afterwards
          }
    
          if (bufsz == len)
          {
             // time to resize the buffer.
             //
             void *newbuf = NULL;
             if (!buf)
             {
                bufsz = 512; // some arbitrary starting size.
                newbuf = malloc(bufsz);
             }
             else
             {
                bufsz *= 2; // issue - ideally you'd check for overflow here.
                newbuf = realloc(buf, bufsz);
             }
    
             if (!newbuf)
             {
                // Allocation failure.  Free old buffer (if any) and bail.
                //
                free(buf);
                buf = NULL;
                break;
             }
    
             buf = newbuf;
          }
    
          buf[len++] = c;
       }
    
       return buf;
    }
    

提交回复
热议问题