19. Command Line Arguments (argc, argv) in C

🟢 Difficulty: Beginner to Intermediate | Terminal Flag Parsing, Argument Conversion & Validation

📖 Definition

Command line arguments are parameters passed to a C executable program at invocation time from a terminal or shell prompt. They are received by the main() function via two parameters: int argc (argument count) and char *argv[] (argument vector, an array of string pointers).

🎯 Why It Is Used

  • CLI Utility Automation: Creating command line tools (like gcc, grep, git) that accept input file paths, flags, and configuration settings dynamically without prompting interactively.
  • Script & Pipeline Integration: Allowing C binaries to be executed inside shell scripts and automated build pipelines.

⚙️ How It Works: The argv Structure

Given the terminal command ./myprog input.txt -v 42:

  • argc == 4 (Total count of argument tokens including binary executable name).
  • argv[0] == "./myprog" (Executable program name string).
  • argv[1] == "input.txt" (First user parameter).
  • argv[2] == "-v" (Option flag parameter).
  • argv[3] == "42" (Option argument string).
  • argv[4] == NULL (ISO C guarantees argv[argc] is always a NULL pointer).

📝 Syntax

#include <stdio.h>
#include <stdlib.h> // For strtol(), strtod()

int main(int argc, char *argv[]) { // or char **argv
    if (argc < 2) {
        printf("Usage: %s <input_file>\n", argv[0]);
        return 1;
    }

    // Access argv[1]...
    return 0;
}

🔀 String to Numeric Conversions (strtol vs atoi)

Conversion Function Header Error Handling Ability Recommendation
atoi(str) <stdlib.h> ❌ None (Returns 0 on invalid string input) Legacy / Quick Prototypes
strtol(str, &endptr, 10) <stdlib.h> ✅ Robust (Detects non-numeric characters & overflows) Production Standard
strtod(str, &endptr) <stdlib.h> ✅ Robust (Parses double floating-point) Production Standard

🌱 Beginner Example: Printing Argument Vector

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Total Arguments Count (argc): %d\n", argc);
    printf("Program Executable Name (argv[0]): %s\n", argv[0]);

    printf("=== Command Line Arguments List ===\n");
    for (int i = 0; i < argc; i++) {
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
    }
    return 0;
}

🌼 Intermediate Example: Robust CLI Addition Calculator

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <num1> <num2>\n", argv[0]);
        return 1;
    }

    char *endptr1, *endptr2;
    long num1 = strtol(argv[1], &endptr1, 10);
    long num2 = strtol(argv[2], &endptr2, 10);

    // Validate that inputs were purely numeric
    if (*endptr1 != '\0' || *endptr2 != '\0') {
        fprintf(stderr, "Error: Command line arguments must be valid integers!\n");
        return 1;
    }

    printf("Calculated Sum: %ld + %ld = %ld\n", num1, num2, num1 + num2);
    return 0;
}

🌲 Advanced Example: Command Line Option Flag Parser

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int main(int argc, char *argv[]) {
    bool verbose = false;
    const char *output_filename = "default.out";

    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
            verbose = true;
        } else if (strcmp(argv[i], "-o") == 0) {
            if (i + 1 < argc) {
                output_filename = argv[++i]; // Consume next argument as output filename
            } else {
                fprintf(stderr, "Error: -o option requires a filename argument!\n");
                return 1;
            }
        }
    }

    printf("Verbose Output Mode : %s\n", verbose ? "ENABLED" : "DISABLED");
    printf("Output Destination  : %s\n", output_filename);
    return 0;
}

🔍 Line-by-Line Explanation

  • int main(int argc, char *argv[]): Standard prototype receiving argument count argc and string pointer array argv.
  • strtol(argv[1], &endptr1, 10): Converts string argument to long base-10 integer and sets endptr1 to first non-numeric character.
  • output_filename = argv[++i];: Consumes next argument token when parsing flag option -o.

💻 Expected Terminal Output

$ ./add_cli 15 25
Calculated Sum: 15 + 25 = 40
$ ./flag_parser -v -o result.txt
Verbose Output Mode : ENABLED
Output Destination  : result.txt

⚠️ Common Mistakes & Pitfalls

  • Out-of-Bounds Access (argv[1] without checking argc): Accessing argv[1] when user provides no arguments (argc == 1) causes an instant Segmentation Fault crash. Always verify argc first!
  • Using Unsafe atoi() in Production: atoi("abc") returns 0 without setting error flags, making it impossible to distinguish genuine zero inputs from invalid non-numeric strings. Use strtol() instead.

📌 Important Rules & Limitations

  • argv[0] always holds the executable program name.
  • ISO C guarantees argv[argc] is always a NULL pointer.
  • Use strtol() or strtod() for numeric argument conversion.

🌐 Multilingual Explanation: English

Command line arguments are passed to main(argc, argv). argc contains the count of argument tokens; argv contains the array of string pointers. Use strtol() for safe numeric conversions.

🌐 Multilingual Explanation: Hindi (Roman Script)

Command line arguments terminal se main(argc, argv) mein milte hain. argc total arguments count karta hai, aur argv strings ka array hota hai. Numbers convert karne ke liye strtol() use karein.

🌐 Multilingual Explanation: Marathi (Roman Script)

Command line arguments main(argc, argv) madhye vachle jatat. argc arguments count aani argv strings saathi vapartat.

❓ Practice Questions

  1. What does argv[0] store?
  2. Why is strtol() preferred over atoi() for command line argument parsing?
  3. What is the value of argv[argc] in ISO C?

🚀 Practical Coding Challenge

Write a C program named file_copy_cli.c that accepts command line arguments ./file_copy_cli <source_file> <dest_file>, opens the source file in read mode, and copies its content to the destination file.

🧭 Navigation & Breadcrumbs

← Previous Module: 18. Storage Classes | Master Syllabus | Next Module: 20. Multi-File Projects →