C Command Line Arguments

Introduction

In this chapter, we will learn how to handle command line arguments in C. Command line arguments are a way to provide input to a program at runtime through the command line interface. They allow you to pass information to your program without requiring user interaction within the program itself.

What are Command Line Arguments?

Command line arguments are parameters passed to a program when it is executed. They can be used to control the behavior of the program, specify input files, set configuration options, and more. In C, command line arguments are handled using the parameters of the main function.

Syntax

The main function in C can accept two parameters for handling command line arguments:

int main(int argc, char *argv[])
  • argc (argument count): An integer that represents the number of command line arguments passed to the program, including the program’s name.
  • argv (argument vector): An array of strings (character pointers) that represents the actual command line arguments. argv[0] is the name of the program, and argv[1] to argv[argc-1] are the arguments passed to the program.

Example: Using Command Line Arguments

Let’s look at a simple example to understand how to use command line arguments in a C program.

Example: Printing 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; // Returning 0 to indicate successful execution
}

To compile and run this program from the command line:

gcc -o print_args print_args.c
./print_args arg1 arg2 arg3

Output:

Number of arguments: 4
Argument 0: ./print_args
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

In this example, the program prints the number of command line arguments and each argument’s value.

Practical Use Cases

Example: Summing Numbers Passed as Arguments

Let’s write a program that sums a list of numbers provided as command line arguments.

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

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <number1> <number2> ... <numberN>\n", argv[0]);
        return 1; // Returning 1 to indicate an error
    }

    int sum = 0;
    for (int i = 1; i < argc; i++) {
        sum += atoi(argv[i]); // Convert argument to integer and add to sum
    }

    printf("Sum: %d\n", sum);
    return 0; // Returning 0 to indicate successful execution
}

To compile and run this program from the command line:

gcc -o sum_args sum_args.c
./sum_args 10 20 30 40 50

Output:

Sum: 150

In this example, the program sums the numbers provided as command line arguments and prints the result.

Example: Reading a File Name from Command Line

Let’s write a program that reads the name of a file from the command line and prints its contents.

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

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <filename>\n", argv[0]);
        return 1; // Returning 1 to indicate an error
    }

    FILE *file = fopen(argv[1], "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1; // Returning 1 to indicate an error
    }

    char ch;
    while ((ch = fgetc(file)) != EOF) {
        putchar(ch);
    }

    fclose(file);
    return 0; // Returning 0 to indicate successful execution
}

To compile and run this program from the command line:

gcc -o print_file print_file.c
./print_file example.txt

Output:

<Contents of example.txt>

In this example, the program reads the name of a file from the command line, opens the file, and prints its contents to the standard output.

Handling Invalid Input

It is important to handle invalid input and provide meaningful error messages to the user. Let’s improve the previous example by checking if the file exists and providing a usage message.

Example: Handling Invalid Input

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

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <filename>\n", argv[0]);
        return 1; // Returning 1 to indicate an error
    }

    FILE *file = fopen(argv[1], "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1; // Returning 1 to indicate an error
    }

    char ch;
    while ((ch = fgetc(file)) != EOF) {
        putchar(ch);
    }

    fclose(file);
    return 0; // Returning 0 to indicate successful execution
}

To compile and run this program from the command line:

gcc -o print_file print_file.c
./print_file non_existent_file.txt

Output:

Error opening file: No such file or directory

In this example, if the file does not exist, the program prints an error message and exits gracefully.

Conclusion

Command line arguments in C provide a powerful way to pass information to your program at runtime. By understanding how to handle command line arguments, you can create flexible and user-friendly programs that can be controlled from the command line. This is particularly useful for writing utility programs, scripts, and applications that require configuration or input files. Mastering command line arguments is an essential skill for writing robust and efficient C programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top