What is the best practice for creating a unix / linux command line tool in C / C ++?

I am currently tasked with creating some helper command line utilities for our internal development team. However, I want to know how best to create unix command line tools. I tried looking at the git source code for an example of how to read options and display messages accordingly. However, I am looking for a clear template for creating a tool, reading parameters safely and displaying standard help messages if the user enters an invalid parameter or --help I want to display a help message. Is there a standard library for reading -abcFGH and --parameter and switching, which starts based on the passed parameter?

Command-Line:

 git 

or

 git --help 

Output:

 usage: git [--version] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] [-c name=value] [--help] <command> [<args>] ... 

Command-Line:

 MyTool CommandName --CommandArgs 

Output:

Regardless of this particular team.


So far I have worked:

The code:

 int main(int argc, char **argv) { if(argc < 2) helpMessage(); char* commandParameter = argv[1]; if (strncmp(argv [1],"help", strlen(commandParameter)) == 0) helpMessage(); else if (strncmp(argv [1],"pull", strlen(commandParameter)) == 0) pull(); else helpMessage(); } 

What would be ideal would be like this:

The code:

 int main(int argc, char **argv) { MagicParameters magicParameters = new MagicParameters(argv); switch(magicParameters[1]) { case command1: Command1(); break; case ... case help: default: HelpMessage(); break; } } 
+7
source share
2 answers

getopt_long () is what you are looking for, here is a simple use case:

  static const struct option opts[] = { {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {"message", required_argument, 0, 'm'}, /* And so on */ {0, 0, 0, 0 } /* Sentiel */ }; int optidx; char c; /* <option> and a ':' means it marked as required_argument, make sure to do that. * or optional_argument if it optional. * You can pass NULL as the last argument if it not needed. */ while ((c = getopt_long(argc, argv, "vhm:", opts, &optidx)) != -1) { switch (c) { case 'v': print_version(); break; case 'h': help(argv[0]); break; case 'm': printf("%s\n", optarg); break; case '?': help(argv[0]); return 1; /* getopt already thrown an error */ default: if (optopt == 'c') fprintf(stderr, "Option -%c requires an argument.\n", optopt); else if (isprint(optopt)) fprintf(stderr, "Unknown option -%c.\n", optopt); else fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt); return 1; } } /* Loop through other arguments ("leftovers"). */ while (optind < argc) { /* whatever */; ++optind; } 
+8
source

Take a look at the getopt library.

+2
source

All Articles