Translate

Thursday, June 13, 2013

Program arguments on the command line

.: Program arguments on the command line :.

Although you can make your own routines to read and process the command line used to invoke your
program, everything is more practical when using the C library functions, as in the case of getopt_long ().

The example code that follows is a simple program that processes its arguments and shows on screen.


 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 
 5 #define _GNU_SOURCE
 6 #include <getopt.h>
 7 
 8 int main(int argc, char *argv[]) {
 9 
10  int opt;
11  int verbose_flag=0;
12 
13  struct option longopts[] = {
14  {"help", 0, NULL, 'h'},
15  {"file", 1, NULL, 'f'},
16  {"verbose",0,&verbose_flag,1},
17  {0,0,0,0}};
18 
19     while((opt = getopt_long(argc, argv, ":hf:", longopts, NULL)) != -1) {
20         switch(opt) {
21         case 'h':
22             printf("option: %c\n", opt);
23    printf("%s [-h|--help] [--verbose] [-f|--file <file>] [args]\n",argv[0]);
24             break;
25         case 'f':
26             printf("option %c filename: %s\n", opt, optarg);
27             break;
28         case ':':
29             printf("option %c needs a value\n", optopt);
30             break;
31         case '?':
32             printf("unknown option: %c\n", optopt);
33             break;
34         }
35     }
36 
37  if (verbose_flag != 0)
38   printf("Verbose mode ON!\n");
39  
40     for(; optind < argc; optind++) {
41   printf("optind: %d < argc: %d\n", optind, argc);
42         printf("argument: %s (argv[%d])\n", argv[optind], optind);
43   printf("\n");
44  }
45  
46  while (optind < argc) {
47   printf("optind: %d < argc: %d\n", optind, argc);
48         printf("argument: %s (argv[%d])\n", argv[optind], optind);
49   printf("\n");
50   optind++;
51  }
52 
53  printf("Out of the loop.\nflag: %d\noptind: %d e argc: %d\n", verbose_flag, optind, argc);
54 
55     exit(0);
56 }

No comments:

Post a Comment