Back to: C Tutorials For Beginners and Professionals
Command Line Arguments in C Language with Examples
In this article, I will discuss the Command Line Arguments in C Language with Examples. Please read our previous articles, where we discussed Pointers in C. As part of this article, you will learn what is Command Line Arguments in C Language, their type, and when and how to use Command Line Arguments in C Programs with Examples.
Command Line Arguments in C Language:
In C programming, command line arguments are used to pass arguments to the main function of a program when it starts executing. The user provides these arguments when they run the program from a command line interface. Here’s how they work:
main Function Signature: The main function in C can be written to accept command line arguments by including two parameters: int argc and char *argv[]. Here’s the typical signature:
int main(int argc, char *argv[])
- argc (Argument Count): This is an integer that indicates how many arguments were passed to the program. The count includes the name of the program itself, so argc will always be at least 1.
- argv (Argument Vector): This is an array of character pointers (char *). Each element in this array is a C string (null-terminated array of characters) representing one of the arguments passed to the program. argv[0] is the name of the program, and argv[1] to argv[argc-1] are the command line arguments provided by the user.
Accessing Arguments: To access the command line arguments, you can iterate through the argv array. Here’s a simple example:
#include <stdio.h> int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } return 0; }
Using Arguments: Command line arguments are commonly used for specifying input files, setting options, or providing other data needed by the program. They allow for flexible and dynamic behavior based on user input.
Error Handling: It’s important to ensure that your program gracefully handles situations where the expected number of arguments is not provided or if an argument is not in the format your program expects.
Limitations: There is a limit to the size of command line arguments, which can vary depending on the operating system and its configuration.
How Command Line Arguments Work in C?
Command line arguments in C allow users to interact with a program by passing data to the program when it starts executing. These arguments are specified after the program name in the command line interface. Here’s a deeper look into how they work:
Program Invocation: When a C program is run from the command line, the user can pass additional text after the program name. These are the command line arguments. For example, myprogram arg1 arg2 arg3
main Function: In C, the main function can be designed to accept these arguments. This is done by defining the main with two parameters: int argc and char *argv[]. The prototype looks like this: int main(int argc, char *argv[])
Understanding argc and argv:
- args (Argument Count): This is an integer that represents the number of command line arguments passed, including the name of the program itself. So, in the example above, argc would be 4.
- argv (Argument Vector): This is an array of character strings (or an array of pointers to characters) that hold the actual arguments. argv[0] is the name of the program, and argv[1] to argv[argc-1] are the command line arguments.
How Arguments Are Passed to the Program?
- The operating system passes the command line arguments to the program.
- argc is set to reflect the number of arguments.
- argv is an array of strings, where each string is one of the arguments. This array ends with a NULL pointer.
Accessing Command Line Arguments:
- Inside the main function, you can access each argument using the argv array.
- You can loop through argv using argc as the limit to process each argument.
Example Usage:
#include <stdio.h> int main(int argc, char *argv[]) { printf("Program name: %s\n", argv[0]); for (int i = 1; i < argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } return 0; }
This program will print out the name of the program and all the arguments passed to it.
Program to Understand Command Line Arguments in C Language:
Here’s a basic example to illustrate how command line arguments work in C:
#include <stdio.h> int main(int argc, char *argv[]) { printf("Number of command line arguments: %d\n", argc); for (int i = 0; i < argc; i++) { printf("argv[%d]: %s\n", i, argv[i]); } return 0; }
In this example, if you run the program like this:
./myprogram arg1 arg2 arg3
It will output:
Number of command line arguments: 4
argv[0]: ./myprogram
argv[1]: arg1
argv[2]: arg2
argv[3]: arg3
Command Line Arguments Examples in C
In C programming, command line arguments are used to pass arguments to a program during its execution. These arguments are accessible within the program through the main function’s parameters, typically defined as int argc, char *argv[]. Here’s a basic example to illustrate how command-line arguments can be used in a C program:
Basic Command Line Argument Program:
This program demonstrates how to access command line arguments in C. The argc variable holds the number of command line arguments (including the program name itself), and argv is an array of strings (character pointers) holding the actual 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; }
Each argument, including the program name, is printed with its index.
Sum of Numbers:
This program calculates the sum of integer numbers passed as command-line arguments. atoi(argv[i]) is used to convert the argument strings to integers.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int sum = 0; for (int i = 1; i < argc; i++) { sum += atoi(argv[i]); } printf("Sum: %d\n", sum); return 0; }
Note: argv[0] is the program name, so the loop starts from i = 1.
Argument Checker:
This program checks if exactly two arguments are passed to it (excluding the program name). If not, it prints the correct usage.
#include <stdio.h> int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s arg1 arg2\n", argv[0]); return 1; } printf("Arguments are: %s and %s\n", argv[1], argv[2]); return 0; }
The program expects exactly 3 arguments (argv[0], argv[1], and argv[2]).
File Reading:
This program opens a file whose name is passed as the second command line argument (argv[1]). It checks if exactly one argument is provided (excluding the program name).
#include <stdio.h> int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s filename\n", argv[0]); return 1; } FILE *file = fopen(argv[1], "r"); if (file == NULL) { perror("Error opening file"); return 1; } // Read and process the file fclose(file); return 0; }
The file is opened in read mode, and error handling is performed to check if the file was successfully opened.
String Concatenation:
This program concatenates all string arguments passed to it, separating them with a space.
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char result[1024] = ""; for (int i = 1; i < argc; i++) { strcat(result, argv[i]); strcat(result, " "); } printf("Concatenated String: %s\n", result); return 0; }
The strcat function is used to append each argument to the result string. The loop starts from i = 1 to skip the program name.
These examples cover basic usage of command line arguments in C, including arithmetic operations, string handling, and file operations. They demonstrate the fundamental ways in which a C program can interact with inputs provided at the command line.
When to Use Command Line Arguments in C?
Command line arguments in C are particularly useful in several scenarios. They are best used when you need to provide input to your program, which can vary each time you run it. Here are some common situations when command line arguments are appropriate:
- Configuration Settings: When your program needs to run with different configurations, hardcoding these settings is impractical. For example, set a program’s logging level (verbose, debug, info).
- File Processing: When your program needs to process files, and you want to specify the file names at runtime rather than hardcoding them. For example, a program that reads, writes, or modifies files based on the names provided as arguments.
- Control Program Behavior: To alter the behavior of the program without changing the code. For example, a sorting program might accept an argument to specify ascending or descending order.
- Passing Parameters for Algorithms or Operations: When your program performs operations that require parameters that could change with each run. For example, a program that performs encryption might accept a key as a command line argument.
- Batch Processing: In scripts or batch jobs, you want to run the same program multiple times with different arguments.
- Testing and Debugging: To test different scenarios without recompiling the code. For instance, passing different sets of inputs to test how your program handles them.
- Networking Applications: For specifying IP addresses, port numbers, and other network settings in network-based applications.
- Utility Scripts or Tools: In creating utility tools or scripts that perform specific tasks based on the arguments provided. For example, a backup script that takes a directory path as an argument.
- Integration with Other Programs: When your C program is part of a larger system and needs to integrate with other software, command-line arguments can be used to receive inputs from other parts of the system.
In the next article, I will discuss Enum in the C Language with Examples. In this article, I try to explain command line arguments in C language with examples. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, questions, or comments about this article.