add options to memcp, fix options in memcat
[awesomized/libmemcached] / src / memcp.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <getopt.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include <sys/mman.h>
8 #include <fcntl.h>
9
10 #include <memcached.h>
11
12 static int opt_verbose;
13 static char *opt_servers;
14 static int opt_replace;
15
16 struct memcached_st *parse_opt_servers (struct memcached_st *m,
17 char *opt_servers)
18 {
19 char *s, *hostname;
20 unsigned int portnum;
21 while (s = strsep(&opt_servers, ",")) {
22 hostname = strsep(&s, ":");
23 portnum = atoi(s);
24 memcached_server_add(m, hostname, portnum);
25 }
26 return m;
27 }
28
29 int main(int argc, char *argv[])
30 {
31 memcached_st *memc;
32 char *string;
33 unsigned int x;
34 size_t string_length;
35 uint16_t flags = 0;
36 time_t expires = 0;
37 memcached_return rc;
38
39 static struct option long_options[] =
40 {
41 {"version", no_argument, NULL, OPT_VERSION},
42 {"help", no_argument, NULL, OPT_HELP},
43 {"verbose", no_argument, &opt_verbose, 1},
44 {"debug", no_argument, &opt_verbose, 2},
45 {"servers", required_argument, NULL, OPT_SERVERS},
46 {"flag", required_argument, NULL, OPT_FLAG},
47 {"expire", required_argument, NULL, OPT_EXPIRE},
48 {"set", no_argument, &opt_replace, 0},
49 {"add", no_argument, &opt_replace, 1},
50 {"replace", no_argument, &opt_replace, 2},
51 {0, 0, 0, 0},
52 };
53 int option_index = 0;
54 int option_rv;
55 while (1)
56 {
57 option_rv = getopt_long(argc, argv, "", long_options, &option_index);
58 if (option_rv == -1) break;
59 switch (option_rv) {
60 case 0:
61 if (long_options[option_index].name)
62 break;
63 case OPT_VERSION: /* --version */
64 printf("memcache tools, memcp, v1.0\n");
65 exit(0);
66 break;
67 case OPT_HELP: /* --help */
68 printf("useful help messages go here\n");
69 exit(0);
70 break;
71 case OPT_SERVERS: /* --servers */
72 opt_servers = strdup(optarg);
73 break;
74 case OPT_FLAG: /* --flag */
75 flags = (uint16_t) atoi(optarg);
76 break;
77 case OPT_EXPIRE: /* --expire */
78 expires = (time_t)atoi(optarg);
79 break;
80 case '?':
81 /* getopt_long already printed an error message. */
82 exit(1);
83 default:
84 abort();
85 }
86 }
87
88 memc= memcached_init(NULL);
89 memc= parse_opt_servers(memc, opt_servers);
90
91 while (optind < argc) {
92 char *mptr;
93 struct stat sbuf;
94 int fd;
95 char *ptr;
96
97 fd= open(argv[optind], O_RDONLY);
98
99 if (fd == -1)
100 {
101 fprintf(stderr, "Failed opening %s\n", argv[optind]);
102 continue;
103 }
104
105 (void)fstat(fd, &sbuf);
106 mptr= mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
107
108 ptr= rindex(argv[optind], '/');
109 if (ptr)
110 {
111 ptr++;
112 }
113 else
114 {
115 ptr= argv[optind];
116 }
117
118 rc= memcached_set(memc, ptr, strlen(ptr),
119 mptr, sbuf.st_size,
120 expire, flags);
121
122 munmap(mptr, sbuf.st_size);
123 close(fd);
124 optind++;
125 }
126
127 memcached_deinit(memc);
128
129 return 0;
130 };