Introduction
In this lab, you will learn how to read command-line arguments in a C program using the argc and argv variables. The argc variable represents the total number of arguments passed to the program, while the argv variable is an array that stores the actual argument values.
Read Command-Line Arguments
In this step, you will write a program that reads command-line arguments and prints them to the console.
Create a new C source file named
arguments.cand open it in WebIDE.Add the following code to the
arguments.cfile:#include <stdio.h> int main(int argc, char* argv[]) { printf("Total number of arguments = %d\n\n", argc); printf("Argument No. 1 = %s\n", argv[0]); printf("Argument No. 2 = %s\n", argv[1]); printf("Argument No. 3 = %s\n", argv[2]); return 0; }Save the changes to the
arguments.cfile and close the text editor.Open a terminal or command prompt and navigate to the directory where the
arguments.cfile is located.Compile the
arguments.cfile using the following command:gcc arguments.c -o argumentsRun the compiled program using the following command:
./arguments hello worldObserve the output of the program:
Total number of arguments = 3 Argument No. 1 = ./arguments Argument No. 2 = hello Argument No. 3 = world
Summary
After completing this lab, you will be able to read command-line arguments in a C program using the argc and argv variables. You will understand how to access the total number of arguments and retrieve the values of specific arguments passed to the program.



