From 19ea0a0c7cc3163fe7fa91ebc1f94df19b0fec94 Mon Sep 17 00:00:00 2001 From: Alex 'AdUser' Z Date: Thu, 9 Apr 2015 16:58:22 +1000 Subject: [PATCH] * sampler.c : use getopt() --- src/sampler.c | 91 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 70 insertions(+), 21 deletions(-) diff --git a/src/sampler.c b/src/sampler.c index be7eedc..bbd9fbe 100644 --- a/src/sampler.c +++ b/src/sampler.c @@ -3,45 +3,94 @@ #include "bitmap.h" #include "sample.h" -void usage() { - puts("Usage: imdb-sample "); - exit(EXIT_FAILURE); +#include + +void usage(int exitcode) { + puts( +"Usage: imdb-write \n" +" -b Path to database\n" +); +puts( +" -A , Add sample from 'path' as record 'num'\n" +" -D Delete record \n" +); + exit(exitcode); } int main(int argc, char **argv) { + enum { undef, add, del } mode = undef; + char opt; + const char *db_path = NULL; + const char *sample = NULL; + const char *c = NULL; imdb_db_t db; imdb_rec_t rec; memset(&db, 0x0, sizeof(imdb_db_t)); memset(&rec, 0x0, sizeof(imdb_rec_t)); - if (argc < 4) - usage(); - - rec.num = strtoll(argv[2], NULL, 10); - if (errno != 0) { - puts("arg 1 not a number"); - usage(); - } + if (argc < 3) + usage(EXIT_FAILURE); - if (imdb_open(&db, argv[1], 1) != 0) { - puts(db.errstr); - usage(); + while ((opt = getopt(argc, argv, "b:A:D:")) != -1) { + switch (opt) { + case 'b' : + db_path = optarg; + break; + case 'h' : + usage(EXIT_SUCCESS); + break; + case 'A' : + mode = add; + if ((c = strchr(optarg, ',')) == NULL) + usage(EXIT_FAILURE); + rec.num = atoll(optarg); + sample = c + 1; + break; + case 'D' : + mode = del; + rec.num = atoll(optarg); + break; + default : + usage(EXIT_FAILURE); + break; + } } - if (imdb_sample(&rec, argv[3]) != 0) { - puts("sampler failure"); - usage(); - } + if (db_path == NULL) + usage(EXIT_FAILURE); - if(imdb_write_rec(&db, &rec) < 1) { + if (imdb_open(&db, db_path, 1) != 0) { puts(db.errstr); - usage(); + exit(EXIT_FAILURE); } + switch (mode) { + case add : + if (rec.num == 0 || sample == NULL) + usage(EXIT_FAILURE); + if (imdb_sample(&rec, sample) != 0) { + puts("sampler failure"); + exit(EXIT_FAILURE); + } + if (imdb_write_rec(&db, &rec) < 1) { + puts(db.errstr); + exit(EXIT_FAILURE); + } + bitmap_print(&rec.data[REC_OFF_BM]); + break; + case del : + if (imdb_write_rec(&db, &rec) < 1) { + puts(db.errstr); + exit(EXIT_FAILURE); + } + break; + default: + usage(EXIT_FAILURE); + break; + } imdb_close(&db); - bitmap_print(&rec.data[REC_OFF_BM]); exit(EXIT_SUCCESS); }