Dave's Brain

Browse - Programming Tips - How do I use getopt() to process command-line options?

Date: 2015jul7
Language: C/C++
Level: Beginner

Q.  How do I use getopt() to process command-line options?

A.  Here is an example.

#include <getopt.h> int main(int argc, char *argv[]) { int c; int nargs; char szFileIn[PATH_MAX]; char szFileOut[PATH_MAX]; bool verbose = false; // The allowed options are in the quoted string. // Options with a parameter have a colon. while ((c = getopt(argc, argv, "i:o:v")) != EOF) { switch (c) { case 'i': strlcpy(szFileIn, optarg, sizeof(szFileIn)); break; case 'o': strlcpy(szFileOut, optarg, sizeof(szFileOut)); break; case 'v': verbose = true; break; default: Usage(); } } nargs = argc - optind; if (nargs != 0) Usage(); // nargs is the number of non-option arguments left. // If you want you can iterate over them: for (int i = optind; i < argc; i++) { char *s = argv[i]; } }
Use getopt_line() for long options. https://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Options.html

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.