Command Line Arguments in C

Welcome to our guide on command line arguments in C! In this tutorial, we will explore how to use command line arguments to make your C programs more flexible and interactive.

What are Command Line Arguments?

Command line arguments are values that are passed to a program when it is executed from the command line or terminal. These arguments allow you to provide input to the program without modifying the source code. They can be used to customize the behavior of the program or to pass data to the program for processing.

How to Use Command Line Arguments in C

In C, command line arguments are passed to the main function as parameters. The argc parameter represents the number of command line arguments, and the argv parameter is an array of strings that contains the actual arguments.

Here is an example of a simple C program that prints the command line arguments:

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i;
    
    for(i = 0; i < argc; i++) {
        printf("Argument %d: %sn", i, argv[i]);
    }
    
    return 0;
}

In this program, we use a for loop to iterate over the command line arguments. The printf function is used to print each argument along with its index.

Let’s say you compile this program and run it with the following command:

$ ./program arg1 arg2 arg3

The output will be:

Argument 0: ./program
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

As you can see, the first argument (argv[0]) is always the name of the program itself. The subsequent arguments are the ones you provide when running the program.

Passing Arguments with Spaces

If you need to pass an argument that contains spaces, you can enclose it in double quotes. For example:

$ ./program "hello world" arg2

In this case, the output will be:

Argument 0: ./program
Argument 1: hello world
Argument 2: arg2

The double quotes ensure that the entire string is treated as a single argument, even if it contains spaces.

Command line arguments are a powerful feature of C that allow you to make your programs more versatile and interactive. By using command line arguments, you can customize the behavior of your program and provide input without modifying the source code. This tutorial has provided you with a basic understanding of how to use command line arguments in C. We hope you found it helpful!

Scroll to Top