/* Name: pmuniq.c Purpose: Acts somewhat like the Unix "uniq" command Author: Bill Slough */ #include #include #include #include #include "util.h" #include "arg.h" struct args_t programArgs; void output(char type, int count, char *s); int main(int argc, char *argv[ ]) { FILE *fp; /* file pointer for an input stream */ char *previous; /* previous line of input */ char *current; /* current line of input */ int count; /* number of times the previous line has appeared */ /* process the command-line arguments */ process_args(argc, argv, &programArgs); /* Try to open the input stream for reading */ if (programArgs.inputFile == NULL) fp = stdin; else { fp = fopen(programArgs.inputFile, "r"); if (fp == NULL) { fprintf(stderr, "%s: %s: no such file\n", argv[0], programArgs.inputFile); exit(EXIT_FAILURE); } } /* read the first line, if any, of the input file */ previous = read_line(fp); count = 1; if (previous == NULL) { /* empty file: close the stream and exit */ fclose(fp); return 0; } /* non-empty file: read all remaining lines */ while ((current = read_line(fp)) != NULL) { if (strcmp(previous, current) == 0) { /* extends an existing run... */ count++; free(current); } else { /* this line begins a new run */ output(programArgs.option, count, previous); free(previous); previous = current; count = 1; } } output(programArgs.option, count, previous); free(previous); /* Close the stream */ fclose(fp); return 0; } void output(char type, int count, char *s) { switch (type) { case 'n': printf("%s\n", s); /* all unique lines, without frequency */ break; case 'c': printf("%d %s\n", count, s); /* all unique lines, with frequency */ break; case 'd': if (count > 1) /* only repeated lines */ printf("%s\n", s); break; case 'u': if (count == 1) { /* only non-repeated lines */ printf("%s\n", s); break; } } }