Skip to content
Advertisement

Check for specific command line arguments and then assign them to variables

Obligatory total noob here.

I am making a simple C program that reads some variables from a file from a simple function. What I’m trying to accomplish, however, is to allow whoever calls the program to override the values read from the file if hey so specify in the command line arguments. I would like to have something like this:

char* filename;
int number;
...
readConfig(filename, number, ...);
if (argc > 1) {
    // Check if the variables were in the args here, in some way
    strcpy(filename, args[??]);
    number = atoi(args[??]);
}

I would like the program to be called as

program -filename="path/to/file.txt" -number=3

I figured out I could just tokenize each argument and match it to every assignable variable and discard the others, but I’m pretty sure that there’s a more elegant way to do this (perhaps with getopts?)

Thank you so much for your help.

Advertisement

Answer

I found this on geeksforgeeks:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int opt;

    // put ':' in the starting of the
    // string so that program can
    //distinguish between '?' and ':'
    while((opt = getopt(argc, argv, ":if:lrx")) != -1)
    {
        switch(opt)
        {
            case 'i':
            case 'l':
            case 'r':
                printf("option: %cn", opt);
                break;
            case 'f':
                printf("filename: %sn", optarg);
                break;
            case ':':
                printf("option needs a valuen");
                break;
            case '?':
                printf("unknown option: %cn", optopt);
                break;
        }
    }
    // optind is for the extra arguments
    // which are not parsed
    for(; optind < argc; optind++){
        printf("extra arguments: %sn", argv[optind]);
    }

    return 0;
}

So, when you pass -f, you need to also pass filename, like: ./args -f filename it will say:

$ ./a.out -f file.txt
filename: file.txt

When you pass -i, -l, or -r, or -ilr, it will say:

$ ./a.out -ilr
option: i
option: l
option: r

If you pass -f but without a filename, it will say option needs argument. Anything else will be printed to extra arguments

So, with it, you can add options to getopts, add new case, do a thing, like: getopts(argc, argv, ":fn:") -f filename, -n number, pretty easy

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement