title: how to sort text file in C using struct?
body: <p>I am trying to sort a text file based on member's age. My code doesn't work only because third and fourth lines have last column (town) missing. If all lines have same information ( suppose, 3rd and 4th lines have the name of the town/city), it works fine. In my way, when struct reads 3rd line, it reads first word from 4th line as town/city.</p>
  
  <p>Here is my codes:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  typedef struct _Member{
      char *name;
      int age;
      int id;
      char *town;
  }Member;
  
  int main() {
  
      FILE *file = fopen("member.txt", "r");
      FILE *newFile = fopen("new_member.txt", "w");
  
      int counter=0, line = 10;
      int i;
      Member *member = malloc(sizeof(Member)*line);
  
      for(i =0; i&lt;line; i++){
          int len = 12;
          char *name = malloc(sizeof(char)*(len+1));
          name [len] = '\0';
          int age;
          int id;
          char *town = malloc(sizeof(char)*(len+1));
          town [len] = '\0';
  
          fscanf(file,"%s %i %i %s\n", name, &amp;age, &amp;id, town);
  
          member[counter].name = name;
          member[counter].age = age;
          member[counter].id = id;
          member[counter].town = town;
  
          counter++;
      }
      while(1){
      int swapped = 0, i, j;
      Member temp;
      for (i = 1; i &lt; counter; i++){
          for(j = 0; j &lt;counter - i; j++){
          if(member[j].age &gt; member[j+1].age){
              temp = member[j];
              member[j]=member[j+1];
              member[j+1] = temp;
              swapped = 1;
          }
          }
      }
      if(swapped ==0){
          break;
      }
      }
  
      for(i = 0; i &lt; counter; i++){
          fprintf(newFile,"%s %d %d %s\n", member[i].name, member[i].age, member[i].id, member[i].town);
      }
  
      fclose(file);
      fclose(newFile);
  
      printf("Successful\n");
  
      return 0;
  }
  </code></pre>
  
  <p>member.txt file:</p>
  
  <pre><code>John 23 3456 Edinburgh
  Robert 33 4567 London
  Peter 45 4345 
  Cary 56 12345 
  Diane 45 4587 Norfolk
  Will 32 3453 Essex
  Paul 56 7896 York
  Alisha 78 1234 Peterbourgh
  Brandon 45 3214 Brighton
  Eli 39 5234 Oxford
  </code></pre>
  
  <p>result after sorting; new_member.txt file</p>
  
  <pre><code>John 23 3456 Edinburgh
  Will 32 3453 Essex
  Robert 33 4567 London
  Eli 39 5234 Oxford
  Peter 45 4345 Cary
  Diane 45 4587 Norfolk
  Brandon 45 3214 Brighton
  Paul 56 7896 York
  Alisha 78 1234 Peterbourgh
  56 12345 4345 
  </code></pre>
  
  <p>How can I solve this problem? or what may be the other approach to sort this type of files? Any help will be appreciated. Thanks</p>