diff options
Diffstat (limited to 'uniq.c')
-rw-r--r-- | uniq.c | 45 |
1 files changed, 38 insertions, 7 deletions
@@ -28,28 +28,59 @@ | |||
28 | #include <string.h> | 28 | #include <string.h> |
29 | #include <errno.h> | 29 | #include <errno.h> |
30 | 30 | ||
31 | static int print_count; | ||
32 | static int print_uniq = 1; | ||
33 | static int print_duplicates = 1; | ||
34 | |||
35 | static void print_line(char *line, int count, FILE *fp) | ||
36 | { | ||
37 | if ((print_duplicates && count > 1) || (print_uniq && count == 1)) { | ||
38 | if (print_count) | ||
39 | fprintf(fp, "%7d\t%s", count, line); | ||
40 | else | ||
41 | fputs(line, fp); | ||
42 | } | ||
43 | } | ||
44 | |||
31 | int uniq_main(int argc, char **argv) | 45 | int uniq_main(int argc, char **argv) |
32 | { | 46 | { |
33 | FILE *in = stdin, *out = stdout; | 47 | FILE *in = stdin, *out = stdout; |
34 | char *lastline = NULL, *input; | 48 | char *lastline = NULL, *input; |
49 | int opt, count = 0; | ||
35 | 50 | ||
36 | /* parse argv[] */ | 51 | /* parse argv[] */ |
37 | if ((argc > 1 && **(argv + 1) == '-') || argc > 3) | 52 | while ((opt = getopt(argc, argv, "cdu")) > 0) { |
38 | usage(uniq_usage); | 53 | switch (opt) { |
54 | case 'c': | ||
55 | print_count = 1; | ||
56 | break; | ||
57 | case 'd': | ||
58 | print_duplicates = 1; | ||
59 | print_uniq = 0; | ||
60 | break; | ||
61 | case 'u': | ||
62 | print_duplicates = 0; | ||
63 | print_uniq = 1; | ||
64 | break; | ||
65 | } | ||
66 | } | ||
39 | 67 | ||
40 | if (argv[1] != NULL) { | 68 | if (argv[optind] != NULL) { |
41 | in = xfopen(argv[1], "r"); | 69 | in = xfopen(argv[optind], "r"); |
42 | if (argv[2] != NULL) | 70 | if (argv[optind+1] != NULL) |
43 | out = xfopen(argv[2], "w"); | 71 | out = xfopen(argv[optind+1], "w"); |
44 | } | 72 | } |
45 | 73 | ||
46 | while ((input = get_line_from_file(in)) != NULL) { | 74 | while ((input = get_line_from_file(in)) != NULL) { |
47 | if (lastline == NULL || strcmp(input, lastline) != 0) { | 75 | if (lastline == NULL || strcmp(input, lastline) != 0) { |
48 | fputs(input, out); | 76 | print_line(lastline, count, out); |
49 | free(lastline); | 77 | free(lastline); |
50 | lastline = input; | 78 | lastline = input; |
79 | count = 0; | ||
51 | } | 80 | } |
81 | count++; | ||
52 | } | 82 | } |
83 | print_line(lastline, count, out); | ||
53 | free(lastline); | 84 | free(lastline); |
54 | 85 | ||
55 | return EXIT_SUCCESS; | 86 | return EXIT_SUCCESS; |