int main( int argc, char * argv[] )Here argc is the number of command line arguments (including the name of the executable), and argv is an array of the arguments.
Invoke the emacs editor to write a program called cmdargs.c as follows:
emacs cmdargs.cRemember to save your code frequently with CTRL-X CTRL-S, use CTRL-G when stuck in the editor, and CTRL-X CTRL-C to exit the editor.
Type the following program in your file cmdargs.c:
int main( int argc, char * argv[] ) { int i; printf("\nYour program name is %s\n", argv[0]); printf("Your arguments are: \n"); for(i = 1; i < argc; i++) printf("\t %s starts with %c\n", argv[i], argv[i][0]); return 0; }Save your program (CTRL-X CTRL-S) and then exit (CTRL-X CTRL-C). Compile your code using the command
gcc cmdargs.c -o cmdargsPay careful attention to error and warning messages, and eliminate them all. To execute your program, use the command
./cmdargs let us see what this doesInspect the output of your code and analyze the code to answer the following questions
man atoiYou will find out that the atoi function takes a string (char * in C) as an argument, and converts it to an integer. For instance, in the C statement
num = atoi("123")the atoi function takes as argument the string "123" and returns the integer value 123 (one hundred and twenty three) in the integer variable num (which must be defined earlier in your code).
./sumargs 7 11The output in this case should be 1. Have your program print an error message in case the command line is invalid:
if(argc < 3) { printf("Invalid command line: supply two integers \n"); exit(1); }Note that you'll need to use the atoi function to convert the arguments (which are strings) to integer values.
Leave the source code for all exercises in your directory csc1600/cmdargs, and do not make any changes to these files after the due date for this assignment. If you wish to continue working on these exercises after the due date, make a copy of your directory cmdargs using the following Unix commands:
cp -r ~/csc1600/cmdargs ~/csc1600/cmdargs-copyA new directory called cmdargs-copy will be created in your csc1600 directory. You may now make any changes you want to the files in your cmdargs-copy directory, at any time.
Have fun!