Browse code

Use optparse, support --help, --version

John Hawthorn authored on 20/08/2014 02:16:24
Showing 1 changed files

  • fzy.c index 510ac31..b015e99 100644
... ...
@@ -3,6 +3,7 @@
3 3
 #include <string.h>
4 4
 #include <stdlib.h>
5 5
 #include <ctype.h>
6
+#include <getopt.h>
6 7
 
7 8
 #include "fzy.h"
8 9
 #include "tty.h"
... ...
@@ -215,18 +216,40 @@ void run(tty_t *tty){
215 216
 	}while(1);
216 217
 }
217 218
 
219
+static const char *usage_str = ""
220
+"USAGE: fzy [OPTION]...\n"
221
+" -h, --help     display this help and exit\n"
222
+" -v, --version  output version information and exit\n";
223
+
218 224
 void usage(const char *argv0){
219
-	fprintf(stderr, "USAGE: %s\n", argv0);
225
+	fprintf(stderr, usage_str, argv0);
220 226
 	exit(EXIT_FAILURE);
221 227
 }
222 228
 
229
+static struct option longopts[] = {
230
+	{ "version", no_argument, NULL, 'v' },
231
+	{ "help",    no_argument, NULL, 'h' },
232
+	{ NULL,      0,           NULL, 0 }
233
+};
234
+
235
+
223 236
 int main(int argc, char *argv[]){
224
-	if(argc == 2 && !strcmp(argv[1], "-v")){
225
-		printf("%s " VERSION  " (c) 2014 John Hawthorn\n", argv[0]);
226
-		exit(EXIT_SUCCESS);
227
-	}else if(argc != 1){
237
+	char c;
238
+	while((c = getopt_long(argc, argv, "vh", longopts, NULL)) != -1){
239
+		switch(c){
240
+			case 'v':
241
+				printf("%s " VERSION " (c) 2014 John Hawthorn\n", argv[0]);
242
+				exit(EXIT_SUCCESS);
243
+			case 'h':
244
+			default:
245
+				usage(argv[0]);
246
+				exit(EXIT_FAILURE);
247
+		}
248
+	}
249
+	if(optind != argc){
228 250
 		usage(argv[0]);
229 251
 	}
252
+
230 253
 	tty_t tty;
231 254
 	tty_init(&tty);
232 255