Sunday 10 January 2021

A Simple And Portable C Command Line Option Parser

I recently had to write some cross platform code with a simple command line parser.

Rather than get caught up in any open source licensing issues I wrote my own.

To use the code, just add your options into parse_command_line () and update the messages in show_help (). 

Here it is, to use as you wish.

// Command line parser
// Copyright (c) 2021 Sigma Numerix Ltd
#include <stdlib.h>
#include <stdio.h>

// Command line options
int     d_number = 0;
int     f_flag = 0;
int     l_flag = 0;
char    s_string[80] = "";

void show_help (void);
void parse_command_line (int argc, char *argv[]);
void main (int argc, char *argv[])
{
    parse_command_line (argc, argv);                        //  Parse command line options
    printf ("d_number  : %d\n", d_number);
    printf ("f_flag    : %d\n", f_flag);
    printf ("l_flag    : %d\n", l_flag);
    printf ("s_string[]: \"%s\"\n", s_string);
    exit(0);
}
void parse_command_line (int argc, char *argv[])
{
    for (int argNum = 1; argNum < argc; argNum++) {
        if (*(argv[argNum]) == '-') {
            switch (*(argv[argNum]+1)) {                    // Get command letter
                case 'd':
                    d_number = (unsigned int)atoi(argv[argNum+1]);
                    if ((d_number < 0) || (d_number > 9)) {
                        printf ("Command line error: Debug number range 0..9\n");
                        exit(-1);
                    }
                    argNum++;
                    break;
                case 'f':
                    f_flag = 1;
                    break;
                case 'l':
                    l_flag = 1;
                    break;
                case 'S':
                    strcpy (s_string, argv[argNum+1]);
                    argNum++;
                    break;
                case 'h':
                    show_help ();
                    exit (0);
                    break;
                default:
                    printf ("Invalid parameter combination\n");
                    show_help ();
                    exit (0);
                    break;
            }
        }
        else {
            printf ("Invalid parameter combination\n");
            show_help ();
            exit (0);
        }
    }
}

void show_help (void)
{
    printf ("cmdline Example Program\n\n");
    printf ("usage: cmdline [-fhl] [-d debug_number]\n");
    printf ("   [-s debug_string]\n");
    printf ("       -d  Debug number (default: 0, range 0-9)\n");
    printf ("       -f  f option flag\n");
    printf ("       -l  l option flag\n");
    printf ("       -S  Debug string (default: empty)\n");
    printf ("       -h  Help\n\n");
}