-
Notifications
You must be signed in to change notification settings - Fork 0
/
guniq.c
88 lines (77 loc) · 1.9 KB
/
guniq.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* $Id: guniq.c 281 2006-08-02 18:44:40Z colin $
* guniq -- globally unique'ify input, with instance count.
*/
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include "dict.h"
static int show_counts = 0;
static int show_dot = 0;
static int show_dump = 0;
void dot_count (FILE *out, const void *key, void *value)
{
fprintf (out, "%s: %d", (const char *)key, *(int *)value);
}
int main (int argc, char *argv[])
{
Dict *lines = dict_new (NULL);
DictEntry *de;
int i;
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-c"))
show_counts = 1;
else if (!strcmp(argv[i], "-d"))
show_dot = 1;
else if (!strcmp(argv[i], "-m"))
show_dump = 1;
else
{
fprintf (stderr, "Syntax: %s [-c] [-d]\n", argv[0]);
return EXIT_FAILURE;
}
}
/* Iterate over input lines. */
while (!feof(stdin))
{
char buffer[BUFSIZ];
if (fgets(buffer, BUFSIZ, stdin))
{
char *end;
int *data;
/* chomp the input */
end = buffer;
while (*end && *end != '\n') end++;
*end = '\0';
data = dict_get (lines, buffer);
if (!data)
{
fprintf (stdout, "%s\n", buffer);
data = malloc (sizeof (int));
*data = 0;
dict_insert (lines, buffer, data);
}
(*data)++;
}
}
if (show_counts)
{
/* Iterate over hash and emit counts and strings. */
for (de = dict_first (lines); de; de = dict_next (lines, de))
fprintf (stdout, "%10d %s\n",
*(int *)de->value, (const char *)de->key);
}
if (show_dot)
{
dict_dump_dot (lines, stdout, dot_count);
}
if (show_dump)
{
dict_dump (lines, stdout, dot_count);
}
/* Free. */
for (de = dict_first (lines); de; de = dict_next (lines, de))
free (de->value);
dict_free (lines);
return EXIT_SUCCESS;
}