CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Parsing command-line arguments, continued

Consider the following program, that accepts an optional command switch, -d, and then zero or more filenames:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

char *progname;
bool dflag        = false;

int main(int argc, char *argv[])
{
    progname = argv[0];

    --argc; ++argv;

    while(argc > 0 && (*argv)[0] == '-') {  // or  argv[0][0]
        if((*argv)[1] == 'd')               // or  argv[0][1]
            dflag = !dflag;
        else
            argc = 0;
        --argc; ++argv;
    }
    if(argc < 0) {
        fprintf(stderr, "Usage : %s [-d] [filename]\n", progname);  
        exit(EXIT_FAILURE);
    }
    if(argc > 0) {
        while(argc > 0) {
            process_file(*argv);    // provide filename to function
            --argc; ++argv;
        }
    }
    else {
        process_file(NULL);         // no filename, use stdin or stdout?
    }
    return 0;
}

 


CITS2002 Systems Programming, Lecture 18, p4, 2nd October 2023.