Listing 5 C implementation of Listing 3

/* merge1.c: Merge two sorted files
 *           to standard output */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main(int argc, char *argv[])
{
   FILE *f1, *f2;
   char buf1[BUFSIZ], buf2[BUFSIZ];

   /* Open files */
   if (argc != 3)
      return EXIT_FAILURE;
   f1 = fopen(argv[1],"r");
   f2 = fopen(argv[2],"r");
   if (!f1 || !f2)
      return EXIT_FAILURE;

   /* Do the merge */
   fgets(buf1,BUFSIZ,f1);
   fgets(buf2,BUFSIZ,f2);
   while (!feof(f1) && !feof(f2))
   {
      /* INVARIANT: both buffers
       *            have fresh lines */

      /* Print and refresh
       * the appropriate line */
      if(strcmp(buf1,buf2)<=0>
      {
         fputs(buf1,stdout);
         fgets(buf1,BUFSIZ,f1);
      }
      else
      {
         fputs(buf2,stdout);
         fgets(buf2,BUFSIZ,f2);
      }
   }
   /* INVARIANT: At least one file
    *            has been exhausted */

   /* Empty the remaining file  */
   while (!feof(f1))
   {
      /* INVARIANT: buffer-1 has
       *            a fresh line */
      fputs(buf1,stdout);
      fgets(buf1,BUFSIZ,f1);
   }
   /* INVARIANT: file1 has been exhausted */
   fclose(f1);

   while (!feof(f2))
   {
      /* INVARIANT: buffer-2 has
       *            a fresh line */
      fputs(buf2,stdout);
      fgets(buf2,BUFSIZ,f2);
   }
   /* INVARIANT: file2 has been exhausted */
   fclose(f2);

   return EXIT_SUCCESS;
}

/* Sample execution:
c:>merge1 file1.dat file2.dat
brown
dog
fox
jumped
lazy
over
quick
the
the
*/

/*End of File */