Search code examples
cparsingargumentsprogram-entry-pointargv

Parsing multiple command line arguments in c


I have a test.c program which reads different arguments from the standard input and which should output different stuff depending on the given argument.

For example: ./test.c -a 1 -b 2 -c 3

So I wish I could go and take a certain function according to the letter, and then display something specific according to the number. So a letter is always followed by a number.

Here is my code:

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

    printfile();
    while ((++argv)[0]) {
        if (argv[0][0] == '-') {
            switch (argv[0][1]) {
                case 'a':
                    printf("case a\n"); test1(); break;
                case 'b':
                    printf("case b\n"); test2()); break;    
                case 'c':
                    printf("case c\n"); break;
            }
        }
    }
    return 0;
    
}

Here my code only takes each hyphen followed by a letter. Is it possible to separate them and then put each letter with its number?


Solution

  • The usual way to do this is with the getopt() library.

    But if you want to do it explicitly in your code, you can increment argv within the cases and process the next argument as a parameter.

    int main(int argc, char *argv[]) {
    
        printfile();
        while ((++argv)[0]) {
            if (argv[0][0] == '-') {
                int param;
                switch (argv[0][1]) {
                    case 'a':
                        printf("case a\n"); 
                        argv++;
                        if (argv[0][0]) {
                            param = atoi(argv[0]);
                            test1(param);
                        } else {
                            printf("Missing argument");
                            exit(1);
                        }
                        break;
                    case 'b':
                        printf("case b\n"); 
                        argv++;
                        if (argv[0][0]) {
                            param = atoi(argv[0]);
                            test2(param);
                        } else {
                            printf("Missing argument");
                            exit(1);
                        }
                        break;
                    case 'c':
                        printf("case c\n"); 
                        argv++;
                        if (argv[0][0]) {
                            param = atoi(argv[0]);
                            test3(param);
                        } else {
                            printf("Missing argument");
                            exit(1);
                        }
                        break;
                }
            }
        }
        return 0;
        
    }