Listing 7 Sorts files as large as available memory

/* sort.c */
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

#define MAXLINES 512

int comp(const void *, const void *);

main()
{
   int i;
   size_t nlines, maxlines = MAXLINES;
   static char s[BUFSIZ];
   char **lines = calloc(sizeof(char *), maxlines);

   /* Read file */
   for (nlines = 0; fgets(s,BUFSIZ,stdin); ++nlines)
   {
      if (nlines == maxlines)
      {
         /* Expand array of strings */
         maxlines += MAXLINES;
         lines = realloc(lines,maxlines*sizeof(char *));
         assert(lines);
      }

      /* Store this line */
      lines[nlines] = malloc(strlen(s)+1);
      assert(lines[nlines]);
      strcpy(lines[nlines],s);
   }

   /* Sort */
   qsort(lines,nlines,sizeof lines[0],comp);

   /* Print / free memory */
   for (i = 0; i < nlines; ++i)
   {
      fputs(lines[i],stdout);
      fflush(stdout);
      assert(!ferror(stdout));
      free(lines[i]);
   }
   free(lines);
   return 0;
}

/* Compare function for qsort(): */
int comp(const void *pl, const void *p2)
{
   return strcmp(* (char **) pl, * (char **) p2);
}

/* End of File */