From: Michael Orlitzky Date: Tue, 18 Dec 2012 05:01:42 +0000 (-0500) Subject: Use getopt for option parsing. X-Git-Tag: v0.0.2~5 X-Git-Url: https://gitweb.michael.orlitzky.com/?p=apply-default-acl.git;a=commitdiff_plain;h=9e17a644dfc33bba278205305b308d6d2874d2c1 Use getopt for option parsing. --- diff --git a/src/reapply_default_acl.c b/src/reapply_default_acl.c index a5e9d6c..c48f828 100644 --- a/src/reapply_default_acl.c +++ b/src/reapply_default_acl.c @@ -3,6 +3,7 @@ #include #include /* nftw() et al. */ +#include #include /* dirname() */ #include /* PATH_MAX */ #include @@ -552,55 +553,6 @@ void usage(char* program_name) { } -bool asked_for_flag(int argc, - char* argv[], - const char* short_flag, - const char* long_flag) { - /* - * Check argv for either form of the flag, e.g. -h or --help. - */ - int arg_index = 1; - for (arg_index = 1; arg_index < argc; arg_index++) { - if (!strcmp(argv[arg_index], short_flag)) { - return true; - } - if (!strcmp(argv[arg_index], long_flag)) { - return true; - } - } - - return false; -} - - -bool asked_for_help(int argc, char* argv[]) { - return asked_for_flag(argc, argv, "-h", "--help"); -} - -bool asked_for_recursive(int argc, char* argv[]) { - return asked_for_flag(argc, argv, "-r", "--recursive"); -} - -bool is_flag(const char* arg) { - /* - * Is arg a command-line flag (e.g. --recursive)? - */ - char valid_flags[4][32] = { "-h", - "--help", - "-r", - "--recursive" }; - - int flag_index = 0; - for (flag_index = 0; flag_index < 4; flag_index++) { - if (!strcmp(arg, valid_flags[flag_index])) { - return true; - } - } - - return false; -} - - int reapply_default_acl_nftw(const char *target, const struct stat *s, int info, @@ -665,24 +617,36 @@ int main(int argc, char* argv[]) { return EXIT_FAILURE; } - if (asked_for_help(argc, argv)) { - usage(argv[0]); - return EXIT_SUCCESS; - } - int result = EXIT_SUCCESS; + bool recursive = false; - bool recursive = asked_for_recursive(argc, argv); + struct option long_options[] = { + /* These options set a flag. */ + {"help", no_argument, NULL, 'h'}, + {"recursive", no_argument, NULL, 'r'}, + {NULL, 0, NULL, 0} + }; - int arg_index = 1; - for (arg_index = 1; arg_index < argc; arg_index++) { - /* Don't bother stripping the flags from argv; just ignore - * an argument if it's one of our flags. - */ - if (is_flag(argv[arg_index])) { - continue; + int opt = 0; + + while ((opt = getopt_long(argc, argv, "hr", long_options, NULL)) != -1) { + switch (opt) { + case 'h': + usage(argv[0]); + return EXIT_SUCCESS; + case 'r': + recursive = true; + break; + default: + usage(argv[0]); + return EXIT_FAILURE; } + } + + int result = EXIT_SUCCESS; + int arg_index = 1; + for (arg_index = optind; arg_index < argc; arg_index++) { const char* target = argv[arg_index]; bool reapp_result = false;