|
CEG 333: Introduction to UnixPrabhaker MatetiThe
|
In simple C++ programs, main() takes no arguments. However, the shell can actually pass any number of arguments between zero and three to main:
argc: An integer, number of command-line
arguments.argv: An array of cstrings, one per
command-line argument, in the order given.env: An array of cstrings, one per environment
argument, of the form ENV_VAR_NAME="value".Note: The final element in both the argv
and env arrays is always set to NULL, so it can be
used to test for the end of the array.
Warning: an argc starts counting arguments
from 1; a value of 1 means argv has one value, the
name of the program. But C++ array indexes start from 0, so
argv always has values argv[0] ...
argv[argc-1]. argv[argc] is the final
NULL, not one of the arguments!
A C++ env (outputs every variable/value pair in
the environment string):
#include <cstdio>
using namespace std;
int main(int argc, char *argv[], char *env[]) {
for (int i = 0; env[i]; i++) {
printf("%s\n", env[i]);
}
return 0;
}