emit messages to stderr when write fails
[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
25 memc= memcached_init(NULL);
26
27 options_parse(argc, argv);
28
29 if (opt_servers)
30 parse_opt_servers(memc, opt_servers);
31
32 while (optind <= argc)
33 {
34 string= memcached_get(memc, argv[optind], strlen(argv[optind]),
35 &string_length, &flags, &rc);
36 if (rc == MEMCACHED_SUCCESS)
37 {
38 if (opt_displayflag)
39 {
40 if (opt_verbose)
41 printf("key: %s\nflags: ", argv[optind]);
42 printf("%x\n", flags);
43 }
44 else
45 {
46 if (opt_verbose)
47 printf("key: %s\nflags: %x\nlength: %zu\nvalue: ",
48 argv[optind], flags, string_length);
49 printf("%.*s\n", (int)string_length, string);
50 free(string);
51 }
52 }
53 else
54 {
55 fprintf(stderr, "memcat: %s: memcache error %s\n",
56 argv[optind], memcached_strerror(memc, rc));
57 }
58 optind++;
59 }
60
61 memcached_deinit(memc);
62
63 free(opt_servers);
64
65 return 0;
66 };
67
68
69 void options_parse(int argc, char *argv[])
70 {
71 int option_index= 0;
72 int option_rv;
73
74 static struct option long_options[]=
75 {
76 {"version", no_argument, NULL, OPT_VERSION},
77 {"help", no_argument, NULL, OPT_HELP},
78 {"verbose", no_argument, &opt_verbose, OPT_VERBOSE},
79 {"debug", no_argument, &opt_verbose, OPT_DEBUG},
80 {"servers", required_argument, NULL, OPT_SERVERS},
81 {"flag", no_argument, &opt_displayflag, OPT_FLAG},
82 {0, 0, 0, 0},
83 };
84
85 while (1)
86 {
87 option_rv= getopt_long(argc, argv, "Vhvds:", long_options, &option_index);
88 if (option_rv == -1) break;
89 switch (option_rv)
90 {
91 case 0:
92 break;
93 case OPT_VERBOSE: /* --verbose or -v */
94 opt_verbose = OPT_VERBOSE;
95 break;
96 case OPT_DEBUG: /* --debug or -d */
97 opt_verbose = OPT_DEBUG;
98 break;
99 case OPT_VERSION: /* --version or -V */
100 printf("memcache tools, memcat, v1.0\n");
101 exit(0);
102 break;
103 case OPT_HELP: /* --help or -h */
104 printf("useful help messages go here\n");
105 exit(0);
106 break;
107 case OPT_SERVERS: /* --servers or -s */
108 opt_servers= strdup(optarg);
109 break;
110 case '?':
111 /* getopt_long already printed an error message. */
112 exit(1);
113 default:
114 abort();
115 }
116 }
117 }