munchinthepool
munchinthepool

Reputation: 3

What if there are different numbers of command line arguments; how can I deal with it in C?

// test.c
int main(int argc, char* argv[])
{
   printf("%s \n", argv[1]);
   printf("%s \n", argv[2]);
}

what if I wanna enter

gcc -o test test.c
./test gs -ef

or

./test ls

and so on

When I put in only one argument (ex. ./test date) there is an error message like this (Segmentation fault (core dumped))

When there can come two arguments or one argument in kind like this multiple situations, How can I code that doesn't print error messages?

Upvotes: 0

Views: 123

Answers (2)

Alvin
Alvin

Reputation: 38

argc: Number of arguments passed.

argv: Two-dimensional array that has the arguments passed.

Note that the zeroth position in argv is reserved for the program name, so for example you compiled using gcc -o test test.c, argv[0] will contain test. You could then use argc to loop through argv like so:

while (argc >= 0) {
    printf("%s \n", argv[argc]);
    argc--;
}

This will of cause print the list of arguments backwards ending with the program name.

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

Use the argc argument to check the number of arguments and use elements of argv only if there are enough arguments.

#include <stdio.h>

int main(int argc, char* argv[])
{
   if (argc > 1) printf("%s \n", argv[1]);
   if (argc > 2) printf("%s \n", argv[2]);
}

Upvotes: 1

Related Questions