100 likes | 300 Views
Variable Arguments in C. System Software Fall 2013. A short example. #include <stdio.h> #include <stdlib.h> /* for atoi() */ int main(int argc, char *argv[]) { int m,n; if (argc != 4) { printf("Usage: %s m n filename<br>",argv[0]);
E N D
Variable Arguments in C System Software Fall 2013
A short example #include <stdio.h> #include <stdlib.h> /* for atoi() */ int main(int argc, char *argv[]) { int m,n; if (argc != 4) { printf("Usage: %s m n filename\n",argv[0]); return 1; /* If the input does not match the expected */ } m = atoi(argv[1]); /* convert strings to integers */ n = atoi(argv[2]); printf("%s received m=%i n=%i filename=%s\n",argv[0],m,n,argv[3]); return 0; }
Rules For Variable Arguments • main() is passed two arguments from the shell: an integer and a pointer • Traditionally named • Int argc (array count) • char *argv[] (argument vector) • The name of the program is always passed as an argument, so argc is atleast 1.
Psuedo Code Using Variable Arguments For(i = 1; i <= arc; i++) { if argv[i] == flag execute some code, or set some condition }
Another Example #include <stdio.h> int main (int argc, char *argv[]) { int i=0; printf("\ncmdline args count=%s", argc); /* First argument is executable name only */ printf("\nexe name=%s", argv[0]); for (i=1; i< argc; i++) { printf("\narg%d=%s", i, argv[i]); } printf("\n"); return 0; }
Output • $ ./cmdline_basic test1 test2 test3 test4 1234 56789cmdline args count=7 exe name=./cmdline_basic arg1=test1 arg2=test2 arg3=test3 arg4=test4 arg5=1234 arg6=56789