First of all, you are comparing oranges with appels. argc
stores the number of
arguments. Second, even if you used argv[1]
, the comparison would be still
wrong, because it would be comparing pointers, not the contents. Note that in C
a string is a sequence of characters that terminates to '\0'
-terminating byte.
A char*
variable only points to the start of that sequence. The ==
operator
checks for equality of values, in case of pointers (and string literals), it
compares whether both pointers point to the same location.
When you want to compare strings, you have to compare the strings themselves,
that means you have to compare the contents where the pointers are pointing to.
For strings you have to use the strcmp
function like this:
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc != 2)
{
fprintf(stderr, "usage: %s option\n", argv[0]);
return 1;
}
if(strcmp(argv[1], "-i") == 0)
puts("Test 1");
else if(strcmp(argv[1], "-w") == 0)
puts("Test 2");
else {
fprintf(stderr, "Invalid option '%s'\n", argv[1]);
return 1;
}
return 0;
}
Note that it is important to check first that you have enough command line
arguments (the first if
of my code). If the user didn't pass any argument,
argc
will be 1 and argv[1]
will point to NULL
, which would yield undefined
behaviour if it is passed to strcmp
. That's why I only do strcmp
when I'm
100% sure that argv[1]
is not NULL
.
Also if you are coding for a POSIX system (linux, mac, etc), then I recommend using
getopt
for parsing of the command line arguments.