C programming/Command line options

From Teknologisk videncenter
Jump to: navigation, search

Example of how to use Command line options.

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void usage( char *name) {
        printf("Usage: \n");
        printf("%s [-l loginname] [-s safetylevel] [-b blocksize]\n",name);
        exit(1);
}

int main( int argc, char *argv[] ) {
        int c;
        extern char *optarg;
        while(( c = getopt(argc,argv, "l:s:b:" )) != EOF ) {    // Loop the arguments
                switch(c) {
                case 'l': printf("l option %s\n",optarg);
                          break;
                case 's': printf("s option %s\n",optarg);
                          break;
                case 'b': printf("b option %s\n",optarg);
                          break;
                default:  usage( argv[0]);
                }
        }
        return(0);
}