81c0a85d6167c40e0cc973a21be9d578f36a34d9
[awesomized/libmemcached] / src / memcat.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <getopt.h>
4 #include <memcached.h>
5
6 #include "client_options.h"
7 #include "utilities.h"
8
9
10 /* Prototypes */
11 void options_parse(int argc, char *argv[]);
12
13 static int opt_verbose= 0;
14 static int opt_displayflag= 0;
15 static char *opt_servers;
16
17 int main(int argc, char *argv[])
18 {
19 memcached_st *memc;
20 char *string;
21 size_t string_length;
22 uint16_t flags;
23 memcached_return rc;
24 memcached_server_st *servers;
25
26 options_parse(argc, argv);
27
28 if (!opt_servers)
29 return 0;
30
31 memc= memcached_init(NULL);
32
33 servers= parse_opt_servers(opt_servers);
34 memcached_server_push(memc, servers);
35 memcached_server_list_free(servers);
36
37 while (optind < argc)
38 {
39 string= memcached_get(memc, argv[optind], strlen(argv[optind]),
40 &string_length, &flags, &rc);
41 if (rc == MEMCACHED_SUCCESS)
42 {
43 if (opt_displayflag)
44 {
45 if (opt_verbose)
46 printf("key: %s\nflags: ", argv[optind]);
47 printf("%x\n", flags);
48 }
49 else
50 {
51 if (opt_verbose)
52 printf("key: %s\nflags: %x\nlength: %zu\nvalue: ",
53 argv[optind], flags, string_length);
54 printf("%.*s\n", (int)string_length, string);
55 free(string);
56 }
57 }
58 else
59 {
60 fprintf(stderr, "memcat: %s: memcache error %s\n",
61 argv[optind], memcached_strerror(memc, rc));
62 }
63 optind++;
64 }
65
66 memcached_deinit(memc);
67
68 free(opt_servers);
69
70 return 0;
71 }
72
73
74 void options_parse(int argc, char *argv[])
75 {
76 int option_index= 0;
77 int option_rv;
78
79 static struct option long_options[]=
80 {
81 {"version", no_argument, NULL, OPT_VERSION},
82 {"help", no_argument, NULL, OPT_HELP},
83 {"verbose", no_argument, &opt_verbose, OPT_VERBOSE},
84 {"debug", no_argument, &opt_verbose, OPT_DEBUG},
85 {"servers", required_argument, NULL, OPT_SERVERS},
86 {"flag", no_argument, &opt_displayflag, OPT_FLAG},
87 {0, 0, 0, 0},
88 };
89
90 while (1)
91 {
92 option_rv= getopt_long(argc, argv, "Vhvds:", long_options, &option_index);
93 if (option_rv == -1) break;
94 switch (option_rv)
95 {
96 case 0:
97 break;
98 case OPT_VERBOSE: /* --verbose or -v */
99 opt_verbose = OPT_VERBOSE;
100 break;
101 case OPT_DEBUG: /* --debug or -d */
102 opt_verbose = OPT_DEBUG;
103 break;
104 case OPT_VERSION: /* --version or -V */
105 printf("memcache tools, memcat, v1.0\n");
106 exit(0);
107 break;
108 case OPT_HELP: /* --help or -h */
109 printf("useful help messages go here\n");
110 exit(0);
111 break;
112 case OPT_SERVERS: /* --servers or -s */
113 opt_servers= strdup(optarg);
114 break;
115 case '?':
116 /* getopt_long already printed an error message. */
117 exit(1);
118 default:
119 abort();
120 }
121 }
122 }