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

后端 未结 4 1449
生来不讨喜
生来不讨喜 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:30

    This alternative approach is similar to @asveikau's, but economize on the use of malloc() by copying on the stack.

    Please do not use this for homework answer.

    #include 
    #include 
    #include 
    char * slurponeline(FILE *f, int s) {
     const int size = 4096;
     char buffer[size];
     char * r;
     int c,i=0;
     while( i=0 && c!='\n')) buffer[i++]=c;
     if (0 == s && 0 == i) return 0;
     r = (size==i)? slurponeline(f,s+size):malloc(s+i);
     memcpy(r+s,buffer,i);
     return r;
    }
    int main(int argc, char ** argv) {
     FILE * f = fopen(argc>1?argv[1]:"a.out","rb");
     char * a,*command,*commandend,*name,*nameend;
     int age;
     while (a = slurponeline(f,0)) {
      char * p = a;
      while (*p && *p == ' ') ++p; // skip blanks.
      command = p;
      while (*p && *p != ' ') ++p; // skip non-blanks.
      commandend = p;
      while (*p && *p == ' ') ++p; // skip blanks.
      name = p;
      while (*p && *p != ' ') ++p; // skip non-blanks.
      nameend = p;
      while (*p && *p == ' ') ++p; // skip blanks.
      age = atoi(p);
      *commandend=0;
      *nameend=0;
      printf("command: %s, name: %s, age: %d\n",command,name,age);
      free(a);
     }
    }
    

提交回复
热议问题