uniqline.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 NOFILE -1
enum boolean{ FALSE, TRUE };

int help(void);

int main(int argc, char *argv[]){
  FILE *readfile = stdin;
  int readfile_opened = 0;
  char leadbuffer[MAXCOL];
  char laterbuffer[MAXCOL];
  int i, file = NOFILE, count, cnt = 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 'c':
        cnt = 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;
  }
  
  if ( fgets(leadbuffer, MAXCOL, readfile) == NULL ) return(EXIT_SUCCESS);
  
  for( count = 1 ; fgets(laterbuffer, MAXCOL, readfile) != NULL ; count++ ){
    if ( strcmp(leadbuffer, laterbuffer) == 0 ) continue;
    if (cnt) fprintf(stdout, "%3d %s", count, leadbuffer);
    else fputs(leadbuffer, stdout);
    strcpy(leadbuffer, laterbuffer);
    count = 0;
  }
  
  if (readfile_opened) fclose(readfile);
  return EXIT_SUCCESS;
}

int help(void){
  fputs("uniqline:\n", stderr);
  fputs("\tIdenticial Lines Remove.\n", stderr);
  fputs("\n", stderr);
  fputs("USAGE:  uniqline [-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("-c       :  with identified times\n", stderr);
  fputs("\n", stderr);
  return EXIT_SUCCESS;
}