
/*
 * exercise in POSIX, strings, character
 * conversion and arrays.
 *
 * void type, casting, 
 * pointers to functions,
 * application: qsort ( and friends ) 
 *
 * burton rosenberg
 * march 2005
 *
 */

#include<stdio.h>   /* fopen, fgets, fclose */
#include<string.h>  /* strtok */
#include<stdlib.h>  /* atoi */ /* qsort */

#define USAGE "usage: %s filename filename\n"
#define BUFFER_SIZE 1024
#define DELIM " \t\n" 
#define ARRAY_SIZE 1024 


int mycompar(const void * a, const void * b) {
   return *((int *) a) - *((int *) b) ;
}

int main(int argc, char * argv[]) {

   FILE * fin, * fout ;
   char line[BUFFER_SIZE] ;
   char * s ;
   int * a ;
   int alen ;
   int i ;

   a = (int *) malloc(ARRAY_SIZE*sizeof(int)) ;
   if ( !a ) exit(0) ;

   if ( argc != 3 ) {
      printf( USAGE, argv[0] ) ;
      exit(0) ;
   }

   fin = fopen( argv[1], "r" ) ;
   if ( fin==NULL ) {
      printf("error: cannot open file %s for read\n", argv[1] ) ;
      exit(1)  ;
   }

/*
   fout = fopen( argv[2], "w" ) ;
   if ( fout==NULL ) {
      printf("error: cannot open file %s for write\n", argv[2] ) ;
      exit(1)  ;
   }
*/

   i = 0 ;
   while ( fgets(line, BUFFER_SIZE, fin) ) {
      s = strtok(line, DELIM) ;
      while ( s ) {

        if ( i>=ARRAY_SIZE) break ;

        a[i++] = atoi(s) ;
        s = strtok(NULL, DELIM) ;
      }
   }
   alen = i ;

   qsort( a, alen, sizeof(int), mycompar) ;

   for ( i=0; i<alen; i++ ) printf("%d\n", a[i] ) ;

   fclose(fin) ;
/*
   fclose(fout) ;
*/

}

