Command-line arguments

Lesson 8.2: Command-Line Arguments


In this lesson, you'll learn how to make your C programs more flexible by allowing them to accept input directly from the command line. This is a valuable skill for creating tools and utilities that can be customized by the user.


What are Command-Line Arguments?


Extra information you provide to your program when you run it from the terminal or command prompt.

Examples:

File names to open.

Options to control the program's behavior (e.g., -v for verbose output).

Numeric values to use in calculations.

Accessing Command-Line Arguments in C


C provides two arguments to the main function to handle command-line arguments:


argc (argument count): An integer that stores the number of arguments passed, including the program's name itself.

argv (argument vector): An array of strings where each element holds one command-line argument.

C

#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;

}

Explanation:


argc: Contains the count of command-line arguments. The program's name is considered the first argument, so argc will always be at least 1.

argv: An array of character pointers (char *), where each pointer points to a string representing one command-line argument.

argv[0] is the name of the program itself.

argv[1] is the first argument after the program name, and so on.

argv[argc] is a null pointer (NULL), marking the end of the array.

Example: Echo Program


Bash

./echo hello world

Output:


Number of arguments: 3

Argument 0: ./echo

Argument 1: hello

Argument 2: world

Parsing Command-Line Arguments


Often, you'll need to parse command-line arguments to extract specific values or options.

You can use libraries like getopt() or write your own logic to interpret the arguments based on your program's needs.

C

#include <stdio.h>

#include <unistd.h> // For getopt() (Linux/macOS)


int main(int argc, char *argv[]) {

    int opt;


    while ((opt = getopt(argc, argv, "vf:")) != -1) {

        switch (opt) {

            case 'v':

                printf("Verbose mode on\n");

                break;

            case 'f':

                printf("Filename: %s\n", optarg); 

                break;

            default:

                fprintf(stderr, "Usage: %s [-v] [-f filename]\n", argv[0]);

                return 1; // Exit with error code

        }

    }

    return 0;

}


Key Points:


Command-line arguments provide flexibility to your programs.

The main function receives argc and argv to handle them.

Use parsing to interpret and extract information from command-line arguments.

Let me know if you have any other questions!

Course Syllabus