Reputation: 3
// 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
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
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