C Programming - Beginner to Brilliance / Advanced Topics

Command Line Arguments

Command Line Arguments allow users to pass inputs to a program at the time of running it, rather than giving input during execution.

✅ They are essential for building flexible and dynamic programs, commonly used in real-world tools, automation scripts, compilers, etc.


🧠 Why Do We Need Command Line Arguments?

Imagine you're creating a file-copy program like:

$ ./filecopy source.txt destination.txt

Here:

  • ./filecopy is the program name

  • source.txt and destination.txt are command line arguments

They allow your program to:

  • Accept input from the user at runtime

  • Automate actions (used in shell scripts, pipelines)

  • Reduce manual input prompts


🔧 Basic Syntax of main() with Command Line Arguments

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

OR

int main(int argc, char **argv)

Term

Meaning

argc

Argument Count – Number of arguments passed to the program (including program name)

argv

Argument Vector – Array of strings (character pointers), each containing one argument


🔍 How It Works

./program Hello World

Now:

  • argc = 3

  • argv[0] = "./program"

  • argv[1] = "Hello"

  • argv[2] = "World"

📌 Always remember:

  • argv[0] is always the program name

  • The rest are actual arguments passed by the user


🧪 Simple Example

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

If you run:

./myProgram Apple Banana

Number of arguments: 3
Argument 0: ./myProgram
Argument 1: Apple
Argument 2: Banana

🎯 Real Use Case: Sum Two Numbers via CLI

#include <stdio.h>
#include <stdlib.h>  // For atoi()

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

    int a = atoi(argv[1]);  // Convert string to int
    int b = atoi(argv[2]);
    printf("Sum: %d\\n", a + b);

    return 0;
}
./sum 10 20

Sum: 30

🔐 Important Functions for Command Line Processing

Function

Purpose

atoi()

Convert string to int

atof()

Convert string to float

strcmp()

Compare two strings

strlen()

Get length of string


🧩 Things to Watch Out For

  1. ❗ Always check argc before accessing argv[i] to avoid segmentation fault( your program tries to access memory that it doesn't have permission to use**)**

  2. ⚠️ Use atoi() carefully — it doesn't report conversion errors

  3. 🧹 Consider using strtol() for safer conversion than atoi()

⚠️ Use Case of strtol(): Converting User Input to Integer

🎯 Scenario:

Imagine you're writing a program that asks the user to enter their age, and you need to convert the input string into an integer. You want to ensure that:

  • The input is a valid number

  • There is no garbage input after the number

  • You can detect errors gracefully


❌ Problem with atoi():

char input[] = "25abc";
int age = atoi(input);  // Converts only "25", ignores "abc"

printf("Age: %d\\n", age);  // Output: 25 (but input was invalid!)

👉 atoi() gives no way to detect if conversion was partial or invalid. It simply stops at the first non-digit and continues silently.


✅ Better with strtol():

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

int main() {
    char input[] = "25abc";
    char *endptr;
    long age = strtol(input, &endptr, 10);

    if (*endptr != '\\0') {
        printf("❌ Invalid input. Non-digit characters found: %s\\n", endptr);
    } else {
        printf("✅ Age: %ld\\n", age);
    }
    return 0;
}
❌ Invalid input. Non-digit characters found: abc

💡 Why strtol() is Better Than atoi():

Feature

atoi() ❌

strtol() ✅

Error detection

❌ None

✅ Yes (endptr)

Overflow/underflow check

❌ No

✅ Can be handled

Partial conversion

✅ Silently

❌ Detected

Input validation

❌ Lacks

✅ Robust


🧠 Memory Behind the Scenes

  • argv is an array of pointers

  • These point to memory locations of the strings passed via terminal

  • All command line arguments are passed from OS to your main() function before execution begins


🛠️ Advanced Use Case: Looping Over Arguments

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

This way, you can:

  • Read filenames

  • Handle options like v, -help, -output=

  • Build real CLI tools