2.3 - Using arguments

2.3 - Using arguments

Now that we’ve explored how to collect user input using fgets(), let’s take another step forward by allowing users to pass input directly when running the program using command-line arguments.

In C, command-line arguments are handled using the main() function’s parameters: int argc and char *argv[]. Where argc is the argument count and *argv[] an array of strings representing the arguments.

Here’s a simple example:

#include <stdio.h>

int main(int argc, char *argv[]) {
    // Check if a name was provided as an argument
    if (argc > 1) {
        printf("Hello, %s!\n", argv[1]);
    } else {
        printf("Hello, World!\n");
    }

    // Print the number of arguments passed (including the program name)
    printf("Number of arguments: %d\n", argc);

    // Print all arguments
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }

    return 0;
}

Breaking Down the Code

1. The main() Parameters

int main(int argc, char *argv[])
  • argc: Short for argument count. It tells you how many command-line arguments were passed.
  • argv[]: Short for argument vector. It’s an array of strings (character pointers), each holding one of the arguments, including the program name.

2. Conditional Greeting

if (argc > 1) {
    printf("Hello, %s!\n", argv[1]);
} else {
    printf("Hello, World!\n");
}
  • If the user provides a name as the first argument (argv[1]), the program prints a personalized greeting.
  • If no name is provided, it defaults to "Hello, World!".

3. Looping Over Arguments

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

This loop prints all the arguments passed to the program, showing how data flows into C programs via the command line.

Example Output

When run like this:

./greet Laura Linux

Output:

Hello, Alice!
Number of arguments: 3
Argument 0: ./greet
Argument 1: Laura
Argument 2: Linux

When run with no arguments:

./greet

Output:

Hello, World!
Number of arguments: 1
Argument 0: ./greet

Summary

This version of the program demonstrates how to:

  • Accept input from the command line using argc and argv.
  • Use conditionals to modify behavior based on user input.
  • Loop through arguments to process dynamic data.

Command-line arguments are a powerful way to make your C programs flexible and script-friendly, especially in automation and scripting tasks.



© 2025 Easy and fast Programming guide For C

Powered by Tessera for Jekyll