Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE 103 Engineering Programming Chapter 46 argc, argv, envp

Similar presentations


Presentation on theme: "ECE 103 Engineering Programming Chapter 46 argc, argv, envp"— Presentation transcript:

1 ECE 103 Engineering Programming Chapter 46 argc, argv, envp
Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip PSU ECE

2 Syllabus Command Line Arguments Examples

3 Accessing Command Line Arguments
Command line arguments are extra options that a user can pass to a program that is started from the command line. Format: exec_filename arg1 arg2 arg3 … Arguments are listed after the executable name. Arguments are separated with whitespace. 2

4 gcc –ansi –Wall –pedantic prog.c
One implicit argument always exists, which is the name of the executable file itself. Example: gcc –ansi –Wall –pedantic prog.c The example has five arguments. The gcc is implicit, while the rest are explicit. 3

5 int main (int argc, char * argv[])
By modifying the main() function header, a C program can access command line arguments. Change this: int main (void) To this: int main (int argc, char * argv[]) 4

6 main() function parameters:
argc holds the total number of command line arguments (implicit+explicit). argv is an array of pointers to strings. Each argument value is stored as a string. argv[0] contains the name of the executable. Subsequent argv elements contain the explicit arguments (if any), in the order they appeared on the command line. The final element in argv is always a NULL pointer. 5

7 Example: #include <stdio.h> /* Executable filename is "mygcc" */
/* Executable filename is "mygcc" */ int main (int argc, char * argv[]) { int k; /* Index */ /* Display the number of arguments */ printf("argc = %d\n", argc); /* Display each argument string */ for (k = 0; k < argc; k++) printf("argv[%d] = %s\n", k, argv[k]); return 0; } 6

8 /mygcc –ansi –Wall –pedantic prog.c The output from the program is:
If the command line is: /mygcc –ansi –Wall –pedantic prog.c The output from the program is: argc = 5 argv[0] = /mygcc argv[1] = -ansi argv[2] = -Wall argv[3] = -pedantic argv[4] = prog.c 7

9 The arguments are stored like this in argv:
This is not a 2-D array of characters. It is a 1-D array of pointers to strings. 1 2 3 4 5 6 7 8 9 '/' 'm' 'y' 'g' 'c' '\0' argv[0] argv[1] argv[2] argv[3] argv[4] argv[5] '-' 'a' 'n' 's' 'i' '\0' '-' 'W' 'a' 'l' '\0' '-' 'p' 'e' 'd' 'a' 'n' 't' 'i' 'c' '\0' 'p' 'r' 'o' 'g' '.' 'c' '\0' NULL 8


Download ppt "ECE 103 Engineering Programming Chapter 46 argc, argv, envp"

Similar presentations


Ads by Google