Parsing Command Line Arguments in C

CCBeginner
Practice Now

Introduction

In this project, you will learn how to parse and handle command line arguments in a C program. This is a fundamental skill in software development, as many programs accept and process command line arguments to customize their behavior.

๐Ÿ‘€ Preview

$ gcc cmd.c -o cmd
$ ./cmd --arg1 1 --arg2 demo --arg9 labex
arg1:1
arg2:demo
arg9:labex

๐ŸŽฏ Tasks

In this project, you will learn:

  • How to create a C file and write the basic structure of a C program
  • How to parse command line arguments and extract parameter names and values
  • How to print the parameter names and values in the required format

๐Ÿ† Achievements

After completing this project, you will be able to:

  • Understand the concept of command line arguments and how to use them in a C program
  • Implement a program that can parse and handle command line arguments
  • Apply your knowledge of C programming to solve a practical problem

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/PointersandMemoryGroup -.-> c/pointers("`Pointers`") subgraph Lab Skills c/arrays -.-> lab-301497{{"`Parsing Command Line Arguments in C`"}} c/user_input -.-> lab-301497{{"`Parsing Command Line Arguments in C`"}} c/pointers -.-> lab-301497{{"`Parsing Command Line Arguments in C`"}} end

Create the C File

In this step, you will create the C file for the command line arguments program.

  1. Open a terminal and navigate to the project directory:
cd ~/project
  1. Create a new C file named cmd.c in the project directory:
touch cmd.c
  1. Open the cmd.c file in a text editor and add the following code:
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    // Your code will go here
    return 0;
}

This is the basic structure of the C program that will handle the command line arguments.

Implement the Command Line Argument Parsing

In this step, you will implement the logic to parse the command line arguments and print the parameter names and values.

  1. In the main() function, add a loop to iterate through the command line arguments:
for (int i = 1; i < argc; i++) {
    // Your code will go here
}

The loop starts from index 1 because argv[0] contains the program name.

  1. Inside the loop, check if the current argument starts with --:
if (strncmp(argv[i], "--", 2) == 0) {
    // The argument is a parameter
    char *param = argv[i] + 2; // Remove the leading "--"
    char *value = NULL;

    // Check if there is a value after the parameter
    if (i + 1 < argc && strncmp(argv[i + 1], "--", 2) != 0) {
        value = argv[i + 1];
        i++; // Skip the value argument
    }

    printf("%s:%s\n", param, value);
}

This code extracts the parameter name and value from the command line arguments and prints them in the required format.

  1. The final code is as follows:
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        if (strncmp(argv[i], "--", 2) == 0) {
            char *param = argv[i] + 2; // Remove the leading "--"
            char *value = NULL;

            // Check if there is a value after the parameter
            if (i + 1 < argc && strncmp(argv[i + 1], "--", 2) != 0) {
                value = argv[i + 1];
                i++; // Skip the value argument
            }

            printf("%s:%s\n", param, value);
        }
    }

    return 0;
}
  1. Save the cmd.c file.

Compile and Run the Program

In this step, you will compile the C program and run it with some sample command line arguments.

  1. Compile the cmd.c file:
gcc cmd.c -o cmd

This will create an executable file named cmd.

  1. Run the program with some sample command line arguments:
./cmd --arg1 1 --arg2 demo --arg9 labex

You should see the following output:

arg1:1
arg2:demo
arg9:labex
  1. Try running the program with some duplicate parameters:
./cmd --testarg1 1 --testarg2 demo --testarg1 labex

You should see the following output:

testarg1:1
testarg2:demo
testarg1:labex

Congratulations! You have successfully implemented the command line argument parsing program.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other C Tutorials you may like