** How to use & impliment int argc char argv functionality aka passing arguments to your program **
In order to allow your program to accept arguments, you need to declair 2 items in your main function. Those being integer argc & the charactor argv array. These two items accept the arguments, & allow you to use them inside of your program. This will both be explained in detail, as well examples will be given.
Argc is the integer value of how many arguments have been passed. It is important to remember that the default value will be the command itself. So for example, if 3 arguments are passed, then argv[1] will be the command, giving argc a value of 4 (0 through 4). If your program absolutly must recieve a specific number of arguments, you can use this value to break execution, & then prompt the user on the usage of your program.
Argv is the other value being passed, & it is a charactor array. You can use argv[] to referance each array, or argv[][] to referance each charactor of each array, or a 2d array.
Code example:
#include <stdio.h>
// main program
int main(int argc,char *argv[]) {
int i=1;
// decode arguments
if(argc < 2) {
printf("You must provide at least one argument\n");
exit(0);
}
// report settings
for (;i<argc;i++) printf("Argument %d:%s\n",i,argv[i]);
return(0);
}
Usage examples:
server:/home/user/code>./prog You must provide at least one argument
server:/home/user/code>./prog help me out Argument 1:help Argument 2:me Argument 3:out





MultiQuote





|