sortline.c

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

#define RAISE(msg) {fprintf(stderr, "%s\n", msg);return(EXIT_FAILURE);}
#define MAXCOL 128
#define MAXROW 1024
#define NOFILE -1
enum boolean{ FALSE, TRUE };

void textlines_sort(char *arr[], int len);
int help(void);

int main(int argc, char *argv[]){
  FILE *readfile = stdin;
  int readfile_opened = 0;
  char *textlines[MAXROW];
  int i, row, col = MAXCOL, file = NOFILE, rev = FALSE;
  
  //parse arguments
  for( i = 1; i < argc ; i++ ){
    if (argv[i][0] == '-'){
      if (strcmp(argv[i], "--help") == 0) return help();
      switch(argv[i][1]){
      case 'h':
        return help();
      case 'r':
        rev = TRUE;
        break;
      default:
        RAISE("Illegal option.");
      }
    }else{
      if (file != NOFILE) RAISE("Too many file direction.");
      file = i;
    }
  }
  
  
  if (file != NOFILE){
    readfile = fopen(argv[file], "rt");
    if (readfile == NULL) RAISE("File open error.");
    readfile_opened = 1;
  }
  
  for( i = 0 ; i < MAXROW ; i++ ){
    if ( ( textlines[i] = (char*)malloc(sizeof(char) * col ) ) == NULL ) break;
    if ( fgets(textlines[i], col, readfile) == NULL ) break;
  }
  row = i;
  
  textlines_sort(textlines, row);
  if (rev)
    for( i = row-1 ; i >= 0 ; i-- ) fputs(textlines[i], stdout);
  else
    for( i = 0 ; i < row ; i++ ) fputs(textlines[i], stdout);
  
  
  
  for( i = 0 ; i < row ; i++ ) free(textlines[i]);
  if (readfile_opened) fclose(readfile);
  return EXIT_SUCCESS;
}

void textlines_sort(char *arr[], int len){
  //BUBBLE-SORTING
  int i, j;
  for( j = 0 ; j < len - 1 ; j++ )
    for( i = len - 1 ; i > j ; i-- )
      if (strcmp(arr[i-1], arr[i]) > 0){
        char *w = arr[i];
        arr[i] = arr[i-1];
        arr[i-1] = w;
      }
}

int help(void){
  fputs("sortline:\n", stderr);
  fputs("\tDictionarical Sorting Lines.\n", stderr);
  fputs("\n", stderr);
  fputs("USAGE:  sortline [-o OPTIONS] [FILENAME]\n", stderr);
  fputs("    if you do not direct a file,\n", stderr);
  fputs("  stdin would be readed.\n", stderr);
  fputs("\n", stderr);
  fputs("-h --help:  display help\n", stderr);
  fputs("-r       :  upside down sorting order\n", stderr);
  fputs("\n", stderr);
  return EXIT_SUCCESS;
}