10 static char *getline_wrapped(FILE *file
, unsigned int *linenum
)
14 char *buf
= NOFAIL(malloc(size
));
16 int ch
= getc_unlocked(file
);
24 /* else fall through */
30 buf
= NOFAIL(realloc(buf
, size
+ 1));
35 ch
= getc_unlocked(file
);
42 /* else fall through */
49 buf
= NOFAIL(realloc(buf
, size
));
55 static void write_index(const char *filename
)
57 struct index_node
*index
;
61 cfile
= fopen(filename
, "w");
63 fatal("Could not open %s for writing: %s\n",
64 filename
, strerror(errno
));
66 index
= index_create();
68 while((line
= getline_wrapped(stdin
, NULL
))) {
69 index_insert(index
, line
);
73 index_write(index
, cfile
);
78 static void dump_index(const char *filename
)
82 cfile
= fopen(filename
, "r");
84 fatal("Could not open %s for reading: %s\n",
85 filename
, strerror(errno
));
87 index_dump(cfile
, stdout
, "");
92 static void search_index(const char *filename
, char *key
)
97 cfile
= fopen(filename
, "r");
99 fatal("Could not open %s for reading: %s\n",
100 filename
, strerror(errno
));
102 value
= index_search(cfile
, key
);
104 printf("Found value:\n%s\n", value
);
106 printf("Not found.\n");
112 static void searchwild_index(const char *filename
, char *key
)
114 struct index_value
*values
;
117 cfile
= fopen(filename
, "r");
119 fatal("Could not open %s for reading: %s\n",
120 filename
, strerror(errno
));
122 values
= index_searchwild(cfile
, key
);
124 printf("Found value(s):\n");
126 printf("Not found.\n");
129 struct index_value
*next
= values
->next
;
131 printf("%s\n", values
->value
);
139 static void print_usage(const char *progname
)
142 "Usage: %s [MODE] [FILE] ...\n"
143 " -o, --output <outfile>\n"
144 " -d, --dump <infile>\n"
145 " -s, --search <infile> <key>\n"
146 " -w, --searchwild <infile> <key>\n"
151 static struct option options
[] = {
152 { "output", 0, NULL
, 'o' },
153 { "dump", 0, NULL
, 'd' },
154 { "search", 0, NULL
, 's' },
155 { "searchwild", 0, NULL
, 'w' },
158 int main(int argc
, char *argv
[])
162 char *filename
= NULL
;
165 while ((opt
= getopt_long(argc
, argv
, "odsw", options
, NULL
))
181 print_usage(argv
[0]);
185 print_usage(argv
[0]);
188 print_usage(argv
[0]);
189 filename
= argv
[optind
];
191 if (mode
== 's' || mode
== 'w') {
192 if (optind
+1 >= argc
)
193 print_usage(argv
[0]);
194 key
= argv
[optind
+1];
199 write_index(filename
);
202 dump_index(filename
);
205 search_index(filename
, key
);
208 searchwild_index(filename
, key
);