Difference between revisions of "C programming/Command line options"

From Teknologisk videncenter
Jump to: navigation, search
m
m
 
Line 5: Line 5:
 
#include <string.h>
 
#include <string.h>
 
#include <stdlib.h>
 
#include <stdlib.h>
 +
#include <unistd.h>
 
void usage( char *name) {
 
void usage( char *name) {
 
         printf("Usage: \n");
 
         printf("Usage: \n");

Latest revision as of 06:50, 28 May 2020

Example of how to use Command line options.

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.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);
}