Working multi-segment blerg database
[blerg.git] / blergtool.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "database.h"
4
5 void help() {
6         printf("Usage: blergtool <store|fetch> <storename> [record]\n");
7 }
8
9 int main(int argc, char *argv[]) {
10         if (argc < 2) {
11                 help();
12                 exit(1);
13         }
14
15         if (strncmp(argv[1], "store", 5) == 0) {
16                 char *store = argv[2];
17                 struct blerg *f = blerg_open(store);
18                 if (!f) {
19                         printf("Blerg open failed\n");
20                         exit(1);
21                 }
22
23                 size_t bytes_read = 0;
24                 char *data = malloc(65536);
25                 do {
26                         bytes_read += fread(data + bytes_read, 1, 65536 - bytes_read, stdin);
27                 } while (bytes_read < 65536 && !feof(stdin));
28                 int record = blerg_store(f, data, bytes_read);
29                 blerg_close(f);
30                 free(data);
31
32                 if (record < 0) {
33                         fprintf(stderr, "Could not store\n");
34                         exit(1);
35                 } else {
36                         fprintf(stderr, "Stored record %d\n", record);
37                 }
38         } else if (strncmp(argv[1], "fetch", 5) == 0) {
39                 char *store = argv[2];
40                 int record = atoi(argv[3]);
41                 struct blerg *f = blerg_open(store);
42                 if (!f) {
43                         printf("Blerg open failed\n");
44                         exit(1);
45                 }
46
47                 char *data;
48                 int size;
49                 blerg_fetch(f, record, &data, &size);
50                 blerg_close(f);
51                 fwrite(data, 1, size, stdout);
52                 free(data);
53         } else {
54                 help();
55         }
56
57         return 0;
58 }