Search code examples
cargumentsparameter-passingargvargc

How to count argc in C


I am having problem with, getting right number of parameters:

    while((opt=getopt(argc, argv, ":a:c:SL")) != -1)

If i start script: ./script -a ok -c 1 -S -L argc variable equals to 7

Problem is when i want to start script as ./script -a ok -c 1 -SS -L argc variable equals 7, but it should be 8 cause (SS (or LL/CC) would needs to be count as two).


Solution

  • This sounds like an XY problem. I suspect that the reason you want to count the number of arguments that getopt processes is to access any following arguments that are not options.

    The man page points to the solution:

    If there are no more option characters, getopt() returns -1. Then optind is the index in argv of the first argv-element that is not an option.

    Once your while loop completes, you can do the following:

    int i;
    for (i = optind; i < argc; i++) {
        printf("non-option arument: %s\n", argv[i]);
    }
    

    Alternately, you can move up argv so that it points to the the first non-option argument, and decrement argc accordingly. Then you can start indexing from 0:

    argc -= optind;
    argv += optind;
    int i;
    for (i = 0; i < argc; i++) {
        printf("non-option arument: %s\n", argv[i]);
    }