Read Command-Line Arguments

CBeginner
Practice Now

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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 91% completion rate. It has received a 100% positive review rate from learners.

Read Command-Line Arguments

In this step, you will write a program that reads command-line arguments and prints them to the console.

  1. Create a new C source file named arguments.c and open it in WebIDE.

  2. Add the following code to the arguments.c file:

    #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;
    }
    
  3. Save the changes to the arguments.c file and close the text editor.

  4. Open a terminal or command prompt and navigate to the directory where the arguments.c file is located.

  5. Compile the arguments.c file using the following command:

    gcc arguments.c -o arguments
    
  6. Run the compiled program using the following command:

    ./arguments hello world
    
  7. Observe 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.