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
;
60 unsigned int linenum
= 0;
62 cfile
= fopen(filename
, "w");
64 fatal("Could not open %s for writing: %s\n",
65 filename
, strerror(errno
));
67 index
= index_create();
69 while((line
= getline_wrapped(stdin
, &linenum
))) {
70 pos
= strchr(line
, ' ');
72 index_insert(index
, line
, pos
, linenum
);
76 index_write(index
, cfile
);
81 static struct index_file
*open_index(const char *filename
)
83 struct index_file
*index
;
85 index
= index_file_open(filename
);
88 fatal("%s has wrong magic or version number", filename
);
90 fatal("Could not open %s for reading: %s\n",
91 filename
, strerror(errno
));
97 static void dump_index(const char *filename
)
99 struct index_file
*index
= open_index(filename
);
101 index_dump(index
, stdout
, "");
103 index_file_close(index
);
106 static void search_index(const char *filename
, char *key
)
108 struct index_file
*index
= open_index(filename
);
111 value
= index_search(index
, key
);
113 printf("Found value:\n%s\n", value
);
115 printf("Not found.\n");
118 index_file_close(index
);
121 static void searchwild_index(const char *filename
, char *key
)
123 struct index_file
*index
= open_index(filename
);
124 struct index_value
*values
, *v
;
126 values
= index_searchwild(index
, key
);
128 printf("Found value(s):\n");
130 printf("Not found.\n");
132 for (v
= values
; v
; v
= v
->next
)
133 printf("%s\n", v
->value
);
135 index_values_free(values
);
136 index_file_close(index
);
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
);