title: C Program: Sort a text file with records alphabetical order
body: <p>I am new to file handling and would like some help reading a text file with records for people containing their first and last name, address, city, state, zip code, and phone numbers all separate by "\t", and copy it into another file. The file read can hold any number of records. </p>
  
  <p>I would like to be able to sort these records only by city alphabetically. I am new to file handling so I am not sure how to go about this once reading the file and how to go about it in my comparing function. Also, in my code I have some code commented out that is used to display what each file contains. My issue is when it is not commented out and is part of the program the text file does not copy to the target file. Why is that?</p>
  
  <p>Thank you for the help in advance! My code is here:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;string.h&gt;
  
  typedef struct contacts {
      char fname[1000];
      char lname[1000];
      char address[1000];
      char city[1000];
      char state[1000];
      char zip[1000];
      char num[1000];
  }ContactType;
  
  #define MaxContacts 1000
  ContactType contacts[MaxContacts];
  int ncontacts = 0;// update to number of records stored in contacts[] 
  
  int CompareCity(void *pa, void *pb);
  
  int main()
  {
      char ch, copy, show, source_file[1000], target_file[1000];
      FILE *source, *target;
  
      printf("Enter name of file to copy\n");
      gets(source_file);
  
      source = fopen(source_file, "r");
  
      if (source == NULL)
      {
          printf("Could not open file.\n");
          exit(EXIT_FAILURE);
      }
  
      printf("Enter name of target file\n");
      gets(target_file);
  
      target = fopen(target_file, "w");
  
      if (target == NULL)
      {
          fclose(source);
          printf("Could not open file\n");
          exit(EXIT_FAILURE);
      }
  
      printf("The contents of %s file are :\n", source_file);
  
      /*while ((ch = fgetc(source)) != EOF)
          printf("%c", ch);
      printf("\n");*/
  
      qsort(contacts, ncontacts, sizeof contacts[0], CompareCity);
  
      while ((copy = fgetc(source)) != EOF)
          fputc(copy, target);
  
      printf("File copied successfully.\n");
  
      printf("The contents of %s file are :\n", target_file);
  
      /*while ((show = fgetc(target)) != EOF) 
          printf("%c", show);
      printf("\n");*/
  
      fclose(source);
      fclose(target);
  
      return 0;
  }
  
  int CompareCity(void *pa, void *pb) {
  
      return strcmp(((ContactType*)pa)-&gt;city, ((ContactType*)pb)-&gt;city);
  }
  </code></pre>