pkill
pkill

Reputation: 421

C How to pass exact number of arguments in command line

I am learning C by myself, and I am writing a program that accepts commandline arguments.

main(int argc, char **argv)
chdir (argv[1]);

I was wondering, if there is any way I can limit the number of arguments that can be passed to this program, say, how much number of arguments I pass, it accepts only first 2 only? I was thinking of this because I don't want to keep a huge number of arguments in the program's memory(may be silly thinking).

Upvotes: 0

Views: 99

Answers (1)

Fiddling Bits
Fiddling Bits

Reputation: 8861

There is no way to limit how many arguments the OS can pass to your program programatically... however, you can do one of two things:

  1. Ignore extra arguments
  2. exit with an error.

    #include <stdio.h>
    #include <stdlib.h>
    
    #define EXPECTED_NUMBER_OF_ARGUMENTS (2) 
    
    int main(int argc, char *argv[])
    {
        if(argc != EXPECTED_NUMBER_OF_ARGUMENTS)
        {
            fprintf(stderr, "usage: %s (val)", argv[0]);
            exit(EXIT_FAILURE);
        }
        ...
        exit(EXIT_SUCCESS);
    }
    

Upvotes: 1

Related Questions