Parse Command-Line Arguments in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to parse command-line arguments in C programming. The lab covers the fundamental concepts of command-line arguments, including accessing the number of arguments, retrieving argument values, handling invalid arguments, and implementing a simple command-line tool. By the end of the lab, you will have a solid understanding of how to work with command-line arguments in your C programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/CompoundTypesGroup -.-> c/strings("`Strings`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") subgraph Lab Skills c/output -.-> lab-438243{{"`Parse Command-Line Arguments in C`"}} c/operators -.-> lab-438243{{"`Parse Command-Line Arguments in C`"}} c/if_else -.-> lab-438243{{"`Parse Command-Line Arguments in C`"}} c/strings -.-> lab-438243{{"`Parse Command-Line Arguments in C`"}} c/user_input -.-> lab-438243{{"`Parse Command-Line Arguments in C`"}} c/function_parameters -.-> lab-438243{{"`Parse Command-Line Arguments in C`"}} end

Understand Command-Line Arguments

In this step, you will learn the fundamental concepts of command-line arguments in C programming and how they are passed to a program when it is executed.

What are Command-Line Arguments?

Command-line arguments are parameters that are passed to a program when it is launched from the command line. In C, these arguments are received by the main() function through two special parameters: argc and argv.

  1. Create a new file named arguments_intro.c in the ~/project directory:
cd ~/project
touch arguments_intro.c
  1. Add the following code to explore command-line arguments:
#include <stdio.h>

int main(int argc, char* argv[]) {
    printf("Number of arguments: %d\n", argc);

    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }

    return 0;
}
  1. Compile the program:
gcc arguments_intro.c -o arguments_intro
  1. Run the program with different numbers of arguments:
./arguments_intro
./arguments_intro Hello
./arguments_intro Hello World

Example output:

## When no arguments are provided
Number of arguments: 1
Argument 0: ./arguments_intro

## With one argument
Number of arguments: 2
Argument 0: ./arguments_intro
Argument 1: Hello

## With two arguments
Number of arguments: 3
Argument 0: ./arguments_intro
Argument 1: Hello
Argument 2: World

Understanding argc and argv

  • argc (argument count): Represents the total number of arguments passed to the program, including the program name itself.
  • argv (argument vector): An array of strings containing the actual arguments.
  • argv[0] is always the name of the program.
  • Subsequent arguments start from argv[1].

Access the Number of Arguments

In this step, you will learn how to access and utilize the number of arguments passed to a C program using the argc parameter.

Checking the Number of Arguments

Understanding how to check the number of arguments is crucial for creating flexible and robust command-line programs. You'll learn how to validate the number of arguments and provide appropriate feedback.

  1. Create a new file named argument_count.c in the ~/project directory:
cd ~/project
touch argument_count.c
  1. Add the following code to demonstrate argument count checking:
#include <stdio.h>

int main(int argc, char* argv[]) {
    // Check if the correct number of arguments is provided
    if (argc < 2) {
        printf("Error: At least one argument is required.\n");
        printf("Usage: %s <argument1> [argument2] ...\n", argv[0]);
        return 1;
    }

    // Print the total number of arguments
    printf("Total number of arguments: %d\n", argc);

    // Check for a maximum number of arguments
    if (argc > 4) {
        printf("Warning: Too many arguments. Only first 3 will be processed.\n");
    }

    return 0;
}
  1. Compile the program:
gcc argument_count.c -o argument_count
  1. Run the program with different numbers of arguments:
## No arguments
./argument_count

## One argument
./argument_count Hello

## Multiple arguments
./argument_count Hello World Lab

## Too many arguments
./argument_count Arg1 Arg2 Arg3 Arg4 Arg5

Example output:

## No arguments
Error: At least one argument is required.
Usage: ./argument_count <argument1> [argument2] ...

## One argument
Total number of arguments: 2

## Multiple arguments
Total number of arguments: 4

## Too many arguments
Total number of arguments: 6
Warning: Too many arguments. Only first 3 will be processed.

Key Concepts

  • argc tells you the total number of arguments, including the program name.
  • You can use argc to validate the number of arguments.
  • Provide clear usage instructions when incorrect arguments are given.
  • Handle cases with too few or too many arguments gracefully.

Retrieve Argument Values

In this step, you will learn how to retrieve and process individual argument values using the argv array in a C program.

Accessing and Processing Arguments

Understanding how to access specific argument values is essential for creating interactive command-line tools that can handle user inputs effectively.

  1. Create a new file named argument_values.c in the ~/project directory:
cd ~/project
touch argument_values.c
  1. Add the following code to demonstrate argument value retrieval:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]) {
    // Check if at least two arguments are provided
    if (argc < 3) {
        printf("Usage: %s <name> <age>\n", argv[0]);
        return 1;
    }

    // Retrieve and store argument values
    char* name = argv[1];
    int age = atoi(argv[2]);

    // Validate age
    if (age <= 0) {
        printf("Error: Age must be a positive number.\n");
        return 1;
    }

    // Process and display argument values
    printf("Name: %s\n", name);
    printf("Age: %d\n", age);

    // Demonstrate string comparison
    if (strcmp(name, "LabEx") == 0) {
        printf("Welcome, LabEx user!\n");
    }

    return 0;
}
  1. Compile the program:
gcc argument_values.c -o argument_values
  1. Run the program with different arguments:
## Correct usage
./argument_values LabEx 25

## Incorrect usage
./argument_values
./argument_values John
./argument_values John -5

Example output:

## Correct usage
Name: LabEx
Age: 25
Welcome, LabEx user!

## Incorrect usage (no arguments)
Usage: ./argument_values <name> <age>

## Incorrect usage (missing age)
Usage: ./argument_values <name> <age>

## Incorrect usage (invalid age)
Name: John
Error: Age must be a positive number.

Key Concepts

  • argv[1], argv[2], etc., access specific argument values.
  • atoi() converts string arguments to integers.
  • strcmp() compares strings.
  • Always validate and sanitize input arguments.

Handle Invalid Arguments

In this step, you will learn how to implement robust argument validation and error handling in a C program to manage various types of invalid input scenarios.

Comprehensive Argument Validation

Creating reliable command-line tools requires careful validation of user-provided arguments to prevent unexpected behavior and provide clear error messages.

  1. Create a new file named argument_validation.c in the ~/project directory:
cd ~/project
touch argument_validation.c
  1. Add the following code to demonstrate comprehensive argument validation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// Function to check if a string is a valid number
int is_numeric(const char* str) {
    while (*str) {
        if (!isdigit(*str)) {
            return 0;
        }
        str++;
    }
    return 1;
}

int main(int argc, char* argv[]) {
    // Check for correct number of arguments
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <username> <age>\n", argv[0]);
        fprintf(stderr, "Error: Exactly 2 arguments required.\n");
        return 1;
    }

    // Validate username
    char* username = argv[1];
    if (strlen(username) < 3 || strlen(username) > 20) {
        fprintf(stderr, "Error: Username must be between 3 and 20 characters.\n");
        return 1;
    }

    // Validate age
    char* age_str = argv[2];
    if (!is_numeric(age_str)) {
        fprintf(stderr, "Error: Age must be a positive number.\n");
        return 1;
    }

    int age = atoi(age_str);
    if (age < 0 || age > 120) {
        fprintf(stderr, "Error: Age must be between 0 and 120.\n");
        return 1;
    }

    // Process valid arguments
    printf("Username validated: %s\n", username);
    printf("Age validated: %d\n", age);

    return 0;
}
  1. Compile the program:
gcc argument_validation.c -o argument_validation
  1. Run the program with various input scenarios:
## Correct usage
./argument_validation JohnDoe 30

## Incorrect number of arguments
./argument_validation
./argument_validation JohnDoe

## Invalid username
./argument_validation Jo 30
./argument_validation JohnDoeWithAVeryLongUsername 30

## Invalid age
./argument_validation JohnDoe abc
./argument_validation JohnDoe -5
./argument_validation JohnDoe 150

Example output:

## Correct usage
Username validated: JohnDoe
Age validated: 30

## Incorrect number of arguments
Usage: ./argument_validation <username> <age>
Error: Exactly 2 arguments required.

## Invalid username
Error: Username must be between 3 and 20 characters.

## Invalid age formats
Error: Age must be a positive number.
Error: Age must be between 0 and 120.

Key Concepts

  • Use custom validation functions to check argument formats
  • Implement multiple validation checks
  • Use stderr for error messages
  • Provide clear, informative error feedback
  • Return non-zero exit codes for invalid inputs

Implement a Simple Command-Line Tool

In this step, you will create a practical command-line tool that demonstrates the skills you've learned about parsing and handling command-line arguments.

Calculator Command-Line Tool

You'll implement a simple command-line calculator that performs basic arithmetic operations based on user-provided arguments.

  1. Create a new file named calc.c in the ~/project directory:
cd ~/project
touch calc.c
  1. Add the following code to create a command-line calculator:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Function prototypes
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);

int main(int argc, char* argv[]) {
    // Check for correct number of arguments
    if (argc != 4) {
        fprintf(stderr, "Usage: %s <operation> <num1> <num2>\n", argv[0]);
        fprintf(stderr, "Operations: add, sub, mul, div\n");
        return 1;
    }

    // Parse operation
    char* operation = argv[1];

    // Convert arguments to numbers
    double num1 = atof(argv[2]);
    double num2 = atof(argv[3]);

    // Perform calculation based on operation
    double result = 0;
    if (strcmp(operation, "add") == 0) {
        result = add(num1, num2);
        printf("%.2f + %.2f = %.2f\n", num1, num2, result);
    } else if (strcmp(operation, "sub") == 0) {
        result = subtract(num1, num2);
        printf("%.2f - %.2f = %.2f\n", num1, num2, result);
    } else if (strcmp(operation, "mul") == 0) {
        result = multiply(num1, num2);
        printf("%.2f * %.2f = %.2f\n", num1, num2, result);
    } else if (strcmp(operation, "div") == 0) {
        // Check for division by zero
        if (num2 == 0) {
            fprintf(stderr, "Error: Division by zero\n");
            return 1;
        }
        result = divide(num1, num2);
        printf("%.2f / %.2f = %.2f\n", num1, num2, result);
    } else {
        fprintf(stderr, "Error: Invalid operation\n");
        fprintf(stderr, "Supported operations: add, sub, mul, div\n");
        return 1;
    }

    return 0;
}

// Arithmetic operation functions
double add(double a, double b) {
    return a + b;
}

double subtract(double a, double b) {
    return a - b;
}

double multiply(double a, double b) {
    return a * b;
}

double divide(double a, double b) {
    return a / b;
}
  1. Compile the program:
gcc calc.c -o calc
  1. Run the calculator with different operations:
## Addition
./calc add 5 3

## Subtraction
./calc sub 10 4

## Multiplication
./calc mul 6 7

## Division
./calc div 15 3

## Error cases
./calc div 10 0
./calc pow 5 2

Example output:

## Addition
5.00 + 3.00 = 8.00

## Subtraction
10.00 - 4.00 = 6.00

## Multiplication
6.00 * 7.00 = 42.00

## Division
15.00 / 3.00 = 5.00

## Division by zero
Error: Division by zero

## Invalid operation
Error: Invalid operation
Supported operations: add, sub, mul, div

Key Concepts

  • Combine argument parsing with functional logic
  • Handle different operation scenarios
  • Provide clear error messages
  • Use separate functions for different operations
  • Validate input and handle edge cases

Summary

In this lab, you will learn how to parse command-line arguments in C programming. First, you will understand the fundamental concepts of command-line arguments, including the argc and argv parameters in the main() function. You will then learn how to access the number of arguments and retrieve their values. Additionally, you will explore handling invalid arguments and implement a simple command-line tool. By the end of this lab, you will have the knowledge and skills to effectively utilize command-line arguments in your C programs.

Other C Tutorials you may like