Lesson 54 of 60 – Command Line Arguments in C
90%

Command Line Arguments in C

Command line arguments allow a user to pass values to a C program when the program is started from the command line. These values are received by the main() function.

Note: Command line arguments are commonly accessed through the parameters argc and argv of the main() function.

1. What are Command Line Arguments?

Command line arguments are values supplied to a program when it is started.

For example:

program.exe Rahul 25

Here, Rahul and 25 are command line arguments.

2. Why Use Command Line Arguments?

Command line arguments allow users to provide input without using scanf() while the program is running.

  • Passing file names
  • Passing configuration values
  • Running programs with different options
  • Automation and scripting
  • Passing numbers or text from the command line

3. main() with Command Line Arguments

The common form of main() for command line arguments is:

int main(int argc, char *argv[])
{
    /* program code */
}

The two parameters are argc and argv.

4. What is argc?

argc stands for argument count. It contains the number of command line arguments.

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

The program name is normally included in this count.

5. What is argv?

argv stands for argument vector. It is an array of pointers to character strings containing the command line arguments.

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

Each argument can be accessed using an index.

6. argv[0]

argv[0] normally contains the program name or the path used to invoke the program.

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Program: %s", argv[0]);

    return 0;
}

7. argv[1]

argv[1] contains the first argument supplied after the program name, provided that at least one argument was supplied.

For example:

program.exe Rahul

Here, argv[1] contains "Rahul".

8. argv[2] and Later Arguments

Additional arguments are stored at increasing indexes.

program.exe Rahul 25 India

The arguments are normally:

  • argv[0] → program name
  • argv[1] → Rahul
  • argv[2] → 25
  • argv[3] → India

9. Printing All Arguments

A loop can be used to display all command line arguments.

#include <stdio.h>

int main(int argc, char *argv[])
{
    for(int i = 0; i < argc; i++)
    {
        printf("%s\n", argv[i]);
    }

    return 0;
}

10. argc Example

Suppose the program is started as:

program.exe one two three

Then argc is normally 4 because the program name is included.

argv[0] = program.exe
argv[1] = one
argv[2] = two
argv[3] = three

11. Command Line Arguments are Strings

The values in argv are character strings. Even if the user enters a number, it initially arrives as text.

program.exe 100

The value 100 is initially available as the string "100".

12. Converting a String to an Integer

The atoi() function can convert a string to an integer.

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

int main(int argc, char *argv[])
{
    if(argc > 1)
    {
        int number = atoi(argv[1]);

        printf("Number = %d", number);
    }

    return 0;
}

13. atoi() Function

The atoi() function converts a string representing an integer to an int.

int number = atoi("250");

printf("%d", number);

For robust input validation, functions such as strtol() are generally preferable because they provide better error handling.

14. Converting a String to a Floating-Point Value

The atof() function can convert a string to a double.

#include <stdlib.h>

double price = atof("99.50");

For robust validation, strtod() provides more detailed error handling.

15. Checking argc Before Using argv

Always make sure that the requested argument exists before accessing it.

#include <stdio.h>

int main(int argc, char *argv[])
{
    if(argc > 1)
    {
        printf("Name = %s", argv[1]);
    }
    else
    {
        printf("No name supplied");
    }

    return 0;
}

16. Passing a Name

A name can be passed directly when starting the program.

program.exe Rahul

The program can access the name using:

argv[1]

Since it is a string, it can be printed using %s.

17. Passing Two Numbers

Two numbers can be supplied as command line arguments.

program.exe 10 20

They are initially strings and can be converted before arithmetic.

int a = atoi(argv[1]);
int b = atoi(argv[2]);

18. Adding Command Line Numbers

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

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        printf("Usage: program number1 number2");
        return 1;
    }

    int a = atoi(argv[1]);
    int b = atoi(argv[2]);

    printf("Sum = %d", a + b);

    return 0;
}

If the program is run with 10 20, it calculates their sum.

19. Command Line Arguments with strcmp()

String arguments can be compared using strcmp().

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

int main(int argc, char *argv[])
{
    if(argc > 1)
    {
        if(strcmp(argv[1], "start") == 0)
        {
            printf("Program started");
        }
    }

    return 0;
}

20. Command Line Options

Command line arguments can be used as simple program options.

program.exe start
program.exe stop
program.exe help

The program can inspect argv[1] and decide which operation to perform.

21. Passing a File Name

A file name can be passed to a program instead of asking for it using scanf().

program.exe students.txt

The file name is available through argv[1].

FILE *file = fopen(argv[1], "r");

The argument should be checked before using it.

22. Command Line Arguments and File Handling

#include <stdio.h>

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Usage: program filename");
        return 1;
    }

    FILE *file = fopen(argv[1], "r");

    if(file == NULL)
    {
        printf("Unable to open file");
        return 1;
    }

    printf("File opened successfully");

    fclose(file);

    return 0;
}

23. Multiple Command Line Arguments

A program can accept many arguments.

program.exe Rahul 25 Delhi 85

A loop can process them one by one:

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

24. Arguments Containing Spaces

Arguments containing spaces generally need to be quoted by the command shell.

program.exe "Rahul Kumar"

The quoted text is treated as one command line argument by typical shells.

The program can access it using:

argv[1]

25. Common Mistake: Accessing Missing Arguments

Do not access argv[1], argv[2], or another index without first checking that the argument exists.

if(argc > 2)
{
    printf("%s", argv[2]);
}

This prevents invalid argument access when too few arguments are supplied.

26. Common Mistake: Treating argv as an Integer

Command line arguments are strings, so they cannot be directly treated as integer values.

Incorrect approach:

int number = argv[1];

Instead, convert the string:

int number = atoi(argv[1]);

27. Complete Command Line Calculator

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

int main(int argc, char *argv[])
{
    if(argc != 4)
    {
        printf("Usage: program number operator number");
        return 1;
    }

    int a = atoi(argv[1]);
    int b = atoi(argv[3]);

    if(argv[2][0] == '+')
    {
        printf("Result = %d", a + b);
    }
    else if(argv[2][0] == '-')
    {
        printf("Result = %d", a - b);
    }
    else if(argv[2][0] == '*')
    {
        printf("Result = %d", a * b);
    }
    else if(argv[2][0] == '/')
    {
        if(b == 0)
        {
            printf("Cannot divide by zero");
            return 1;
        }

        printf("Result = %d", a / b);
    }
    else
    {
        printf("Unknown operator");
    }

    return 0;
}

Example command:

program.exe 10 + 20

28. Command Line Arguments vs scanf()

Command Line Arguments scanf()
Input is supplied when starting the program Input is usually entered while the program is running
Values arrive as strings through argv scanf() converts according to its format specifier
Useful for scripts and command-line tools Useful for interactive input

29. Practical Uses of Command Line Arguments

  • Passing file names
  • Running utilities with options
  • Passing configuration values
  • Automating programs with scripts
  • Building command-line tools
  • Providing input to batch programs
  • Selecting program modes
  • Passing numbers and text values

30. Practice Program

Create a C program that:

  1. Accepts a student's name from the command line.
  2. Accepts three marks as command line arguments.
  3. Converts the marks from strings to integers.
  4. Calculates the total marks.
  5. Calculates the average.
  6. Displays the student's name.
  7. Displays the total and average.
  8. Checks that the required number of arguments was supplied.

This exercise will help you practice argc, argv, string conversion, loops, and arithmetic operations.

📌 Key Points

  • Command line arguments allow values to be passed when a program starts.
  • argc stores the number of command line arguments.
  • argv stores the argument strings.
  • argv[0] normally represents the program name or invocation path.
  • argv[1] is normally the first user-supplied argument.
  • Command line arguments are received as strings.
  • atoi() can convert a string to an integer, although strtol() provides stronger error handling.
  • fopen() can use a command line argument as a file name.
  • Always check argc before accessing an argument index.
  • Command line arguments are useful for automation and command-line tools.

🧠 Quick Quiz

Question: Which parameter contains the number of command line arguments?