int main(int argc, char *argv[])
If I have this:
int main(int argc, char *argv[])
In the body, you can sometimes find programs using argv[1]
.
When do we use argv[1]
over argv[0]
? Is it only when we just want to read the second argument in the command line?
By convention , argv[0]
is the current program's name (or path), and argv[1]
through argv[argc - 1]
are the command-line arguments that the user provides.
However, this doesn't have to be true -- programs can OS-specific functions to bypass this requirement, and this happens often enough that you should be aware of it. (I'm not sure if there's much you can do even if you're aware of it, though...)
Example:
gcc -O3 -o temp.o "My file.c"
would (should) produce the following arguments:
argc: 5
argv: ["gcc", "-O3", "-o", "temp.o", "My file.c"]
So saying argv[0]
would refer to gcc
, not to -O3
.
argv
is an array of pointers, and each pointer in this array stores one argument from command line. So argv[0]
is the first argument (that is the executable/program itself), argv[1]
is the second argument, and so on!
The total number of arguments is determined by argc
.
Let's suppose your C++ executable file is:
/home/user/program
(or C:program.exe
in Windows)
if you execute:
./home/user/program 1 2
(or C:program.exe 1 2
in Windows)
argv[0] = /home/user/program
( C:program.exe
)
argv[1] = 1
argv[2] = 2
That is because:
argv[0]
is the path of the executable file argv[1]
is the 1st argument Edit:
Now I see that argv[0]
isn't necessarily the path of the executable file.
Read the following SO question: Is args[0] guaranteed to be the path of execution?