/* Name: pmsort.c Purpose: "Poor man's" sort utility: now with qsort() Author: Bill Slough Usage: pmsort filename */ #include #include #include #include "util.h" int compare_strings(const void *p, const void *q); int main(int argc, char *argv[ ]) { FILE *fp; /* file pointer for an input stream */ char **lines; /* NULL-terminated array of strings */ int i; /* Check for proper usage */ if (argc != 2) { fprintf(stderr, "Usage: pmsort filename\n"); exit(EXIT_FAILURE); } /* Try to open the input stream for reading */ fp = fopen(argv[1], "r"); if (fp == NULL) { fprintf(stderr, "Error: can't open \"%s\" for reading.\n", argv[1]); exit(EXIT_FAILURE); } /* Read and store the lines */ lines = read_lines(fp); /* Process */ qsort(lines, count_lines(lines), sizeof(char *), compare_strings); display_lines(lines); /* Free the space used for the lines */ i = 0; while (lines[i] != NULL) { free(lines[i]); i++; } free(lines); /* Close the stream */ fclose(fp); return 0; } /* compare two string values */ int compare_strings(const void *p, const void *q) { /* Cast the input parameters into the specific types */ const char **p1 = (const char **) p; const char **q1 = (const char **) q; /* return negative, zero, or positive for <, ==, or > */ return strcmp(*p1, *q1); }