d9898ee8 |
1 | /* |
2 | ** Copyright 1998 - 1999 Double Precision, Inc. |
3 | ** See COPYING for distribution information. |
4 | */ |
5 | |
6 | #if HAVE_CONFIG_H |
7 | #include "config.h" |
8 | #endif |
9 | #if HAVE_UNISTD_H |
10 | #include <unistd.h> |
11 | #endif |
12 | #include <stdlib.h> |
13 | #include <string.h> |
14 | #include <stdio.h> |
15 | #include "dbobj.h" |
16 | |
d9898ee8 |
17 | |
18 | static int addgdbm(char *p, struct dbobj *o) |
19 | { |
20 | char *key, *val; |
21 | |
22 | if (!*p || *p == '#') |
23 | return (0); |
24 | |
25 | key=p; |
26 | if ( (val=strchr(p, '\t')) == 0) val=""; |
27 | else *val++=0; |
28 | |
29 | if (*key) |
30 | { |
31 | if (!*val) val="1"; |
32 | if (dbobj_store(o, key, strlen(key), val, strlen(val), "I")) |
33 | { |
34 | fprintf(stderr, "Cannot store record for %s - duplicate or out of disk space.\n", key); |
35 | return (-1); |
36 | } |
37 | } |
38 | return (0); |
39 | } |
40 | |
41 | static int buildgdbm(FILE *i, struct dbobj *o) |
42 | { |
43 | char *buf=0; |
44 | size_t bufsize, buflen; |
45 | |
46 | bufsize=0; |
47 | buflen=0; |
48 | |
49 | for (;;) |
50 | { |
51 | int c; |
52 | |
53 | buflen=0; |
54 | for (;;) |
55 | { |
56 | if (buflen >= bufsize) |
57 | { |
58 | bufsize += 256; |
59 | buf= buf ? realloc(buf, bufsize): |
60 | malloc(bufsize); |
61 | if (!buf) |
62 | { |
63 | perror("malloc"); |
64 | return (-1); |
65 | } |
66 | } |
67 | c=getc(i); |
68 | if (c == '\n' || c == EOF) break; |
69 | buf[buflen++]=c; |
70 | } |
71 | buf[buflen]=0; |
72 | if (c == EOF) return (-1); |
73 | |
74 | if (strcmp(buf, ".") == 0) return (0); |
75 | if (addgdbm(buf, o)) return (-1); |
76 | } |
77 | } |
78 | |
79 | int main(int argc, char **argv) |
80 | { |
81 | FILE *i; |
82 | struct dbobj obj; |
83 | |
84 | if (argc < 4) |
85 | { |
86 | fprintf(stderr, "Usage: %s textfile tmpfile gdbmfile\n", |
87 | argv[0]); |
88 | exit(1); |
89 | } |
90 | if (strcmp(argv[1], "-") == 0) |
91 | i= stdin; |
92 | else |
93 | { |
94 | if ((i=fopen(argv[1], "r")) == 0) |
95 | { |
96 | perror(argv[1]); |
97 | exit(1); |
98 | } |
99 | } |
100 | |
101 | dbobj_init(&obj); |
102 | |
103 | if (dbobj_open(&obj, argv[2], "N")) |
104 | { |
105 | fprintf(stderr, "Cannot create %s\n", argv[2]); |
106 | exit (1); |
107 | } |
108 | |
109 | if (buildgdbm(i, &obj)) |
110 | { |
111 | dbobj_close(&obj); |
112 | unlink(argv[2]); |
113 | exit (1); |
114 | } |
115 | |
116 | dbobj_close(&obj); |
117 | |
118 | if (rename(argv[2], argv[3])) |
119 | { |
120 | perror("rename"); |
121 | unlink(argv[2]); |
122 | exit(1); |
123 | } |
124 | exit(0); |
125 | return (0); |
126 | } |