fix to dont lose the last item on the command line
[awesomized/libmemcached] / src / memcat.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <getopt.h>
4 #include <memcached.h>
5 #include "client_options.h"
6
7 static int opt_verbose;
8 static int opt_displayflag;
9 static char *opt_servers;
10
11 struct memcached_st *parse_opt_servers (struct memcached_st *m,
12 char *opt_servers)
13 {
14 char *s, *hostname;
15 unsigned int portnum;
16 while (s = strsep(&opt_servers, ",")) {
17 hostname = strsep(&s, ":");
18 portnum = atoi(s);
19 memcached_server_add(m, hostname, portnum);
20 }
21 return m;
22 }
23
24 int main(int argc, char *argv[])
25 {
26 memcached_st *memc;
27 char *string;
28 size_t string_length;
29 uint16_t flags;
30 memcached_return rc;
31
32 static struct option long_options[] =
33 {
34 {"version", no_argument, NULL, OPT_VERSION},
35 {"help", no_argument, NULL, OPT_HELP},
36 {"verbose", no_argument, &opt_verbose, 1},
37 {"debug", no_argument, &opt_verbose, 2},
38 {"servers", required_argument, NULL, OPT_SERVERS},
39 {"flag", no_argument, &opt_displayflag, OPT_FLAG},
40 {0, 0, 0, 0},
41 };
42 int option_index = 0;
43 int option_rv;
44
45 while (1)
46 {
47 option_rv = getopt_long(argc, argv, "", long_options, &option_index);
48 if (option_rv == -1) break;
49 switch (option_rv) {
50 case 0:
51 break;
52 case OPT_VERSION: /* --version */
53 printf("memcache tools, memcat, v1.0\n");
54 exit(0);
55 break;
56 case OPT_HELP: /* --help */
57 printf("useful help messages go here\n");
58 exit(0);
59 break;
60 case OPT_SERVERS: /* --servers */
61 opt_servers = strdup(optarg);
62 break;
63 case '?':
64 /* getopt_long already printed an error message. */
65 exit(1);
66 default:
67 abort();
68 }
69 }
70
71 memc= memcached_init(NULL);
72 memc= parse_opt_servers(memc, opt_servers);
73
74 while (optind <= argc) {
75 string= memcached_get(memc, argv[optind], strlen(argv[optind]),
76 &string_length, &flags, &rc);
77 if (rc == MEMCACHED_SUCCESS) {
78 if (opt_displayflag) {
79 printf("%d\n", flags);
80 } else {
81 if (string)
82 {
83 printf("%.*s\n", string_length, string);
84 free(string);
85 }
86 }
87 }
88
89 optind++;
90 }
91
92 memcached_deinit(memc);
93
94 return 0;
95 };