Command line arguments are arguments that are passed to your main() function. Up until now, I've been telling you to ignore 'argc' and 'argv' whenever you've seen them in a program. Now, we're ready to start using them. The command line is the line of text you type when you run your programs, something like: a.out < star10.txt > star.ps
'Arguments' are each of the strings you typed. Anything separated by a space is considered a separate argument. So, this command line has 5 arguments: 'a.out', '<', 'star10.txt', '>', and 'star.ps'.The values of the arguments argc and argv are automatically assigned for you. Thus, you can use these arguments just like you would use arguments passed to any other function.
argc is the value of the number of arguments. For the above example, argc has the value of 5. If you printed argc (in the same way you'd print any other integer value), the number 5 would print. In many programs with command line arguments, you'll want to check the value of argc to make sure that your user is executing your program correctly. For example, if your program required your user to specify a file name for the output produced, you would want to check that argc had the value 2 (a.out & the file name.)
argv is an array of strings. It holds the strings typed on the command line. In the above example, argv[0] is a.out, argv[1] is <, argv[2] is star10.txt,...You can use these strings just like any normal string. As a simple example, consider this program which echos whatever the user types:
void main(int argc, char *argv[]) { int i; for (i = 0; i < argc; i++) puts(argv[i]); }Copy this code into a file and try it. Try changing it around to do other interesting things. (If you come up with any good simple programs, let me know and I'll give it to the rest of the class as a practice exercise.)