Lesson 29
Command Line Arguments
Command Line Arguments allow values to be passed to a C program at execution time through argc and argv. argc stores the total number of arguments including the program name, while argv is an array of strings holding those arguments. Numeric arguments must be converted from strings using functions such as atoi() or strtol().
C Track
Save progress as you learn.
44 lessons
Lesson content
Command Line Arguments in C Programming: A Complete Beginner to Advanced Guide
What are Command Line Arguments in C Programming?
Command Line Arguments are values passed to a C program when it is executed from the command line (terminal or command prompt). They allow users to provide input without modifying the program or entering data interactively.
Instead of prompting the user with scanf(), the program receives the input directly from the command line.
./program Alice 25Here, Alice and 25 are command line arguments.
Think of command line arguments like address information written on a package before delivery. The package (program) receives the information immediately when it starts.
Why Do Command Line Arguments Exist?
Without command line arguments, programs would need to ask users for input every time they run. Command line arguments help to:
- Pass input quickly
- Automate program execution
- Simplify scripting
- Process files specified by the user
- Configure program behavior
Real-World Use Cases
Command line arguments are widely used in:
- File compression tools
- Compilers (like GCC)
- Operating system commands
- Backup utilities
- Database tools
- Image processing programs
- Automation scripts
- Network utilities
Prerequisites
Before learning Command Line Arguments in C Programming, you should understand:
- Variables
- Data types
- Arrays
- Strings
- Functions
- Pointers
- Input and output functions
Core Concepts of Command Line Arguments in C Programming
The main() Function with Arguments
Normally, the main() function is written as:
int main(void)To use command line arguments:
int main(int argc, char *argv[])or equivalently:
int main(int argc, char **argv)Understanding argc
argc stands for Argument Count. It stores the total number of command line arguments, including the program name.
| Argument | Value |
|---|---|
| argv[0] | ./program |
| argv[1] | Alice |
| argv[2] | 25 |
For the command ./program Alice 25, argc equals 3.
Understanding argv
argv stands for Argument Vector. It is an array of pointers to character arrays (strings). Each command line argument is stored as a string.
char *argv[];Converting Arguments to Numbers
Since command line arguments are strings, numeric values must be converted. Common conversion functions:
| Function | Header | Purpose |
|---|---|---|
| atoi() | <stdlib.h> | Convert string to int |
| atof() | <stdlib.h> | Convert string to double |
| strtol() | <stdlib.h> | Convert string to long (recommended) |
| strtod() | <stdlib.h> | Convert string to double (recommended) |
For robust error checking, prefer strtol() and strtod() over atoi() and atof().
Code Examples
Example 1: Beginner – Print All Command Line Arguments
#include <stdio.h> // Include standard input/output library
int main(int argc, char *argv[]) // Program entry point
{
printf("Number of arguments: %d\n", argc); // Print the number of arguments
for (int i = 0; i < argc; i++) // Loop through all arguments
{
printf("argv[%d] = %s\n", i, argv[i]); // Print each argument
}
return 0; // End the program
}Execution: ./program Apple Mango Orange
Output: Number of arguments: 4 / argv[0] = ./program / argv[1] = Apple / argv[2] = Mango / argv[3] = Orange
Example 2: Beginner – Display User Name
#include <stdio.h> // Include standard input/output library
int main(int argc, char *argv[]) // Program entry point
{
if (argc < 2) // Check whether a name was provided
{
printf("Usage: ./program <name>\n"); // Display usage information
return 1; // Exit with an error code
}
printf("Hello, %s!\n", argv[1]); // Print the user's name
return 0; // End the program
}Execution: ./program Alice
Output: Hello, Alice!
Example 3: Intermediate – Add Two Numbers
#include <stdio.h> // Include standard input/output library
#include <stdlib.h> // Include conversion functions
int main(int argc, char *argv[]) // Program entry point
{
if (argc != 3) // Verify the correct number of arguments
{
printf("Usage: ./program <num1> <num2>\n"); // Display usage
return 1; // Exit with an error code
}
int num1 = atoi(argv[1]); // Convert the first argument to an integer
int num2 = atoi(argv[2]); // Convert the second argument to an integer
printf("Sum = %d\n", num1 + num2); // Display the sum
return 0; // End the program
}Execution: ./program 10 20
Output: Sum = 30
Example 4: Intermediate – Process a File Name
#include <stdio.h> // Include standard input/output library
int main(int argc, char *argv[]) // Program entry point
{
if (argc != 2) // Verify the number of arguments
{
printf("Usage: ./program <filename>\n"); // Display usage
return 1; // Exit with an error code
}
FILE *file = fopen(argv[1], "r"); // Open the file specified by the user
if (file == NULL) // Check whether the file opened successfully
{
printf("Unable to open file.\n"); // Print an error message
return 1; // Exit with an error code
}
printf("File opened successfully.\n"); // Print a success message
fclose(file); // Close the file
return 0; // End the program
}Example 5: Advanced – Multiply Numbers Using strtol()
#include <stdio.h> // Include standard input/output library
#include <stdlib.h> // Include strtol()
int main(int argc, char *argv[]) // Program entry point
{
if (argc != 3) // Verify the correct number of arguments
{
printf("Usage: ./program <num1> <num2>\n"); // Display usage
return 1; // Exit with an error code
}
char *endPtr1; // Pointer used by strtol()
char *endPtr2; // Pointer used by strtol()
long num1 = strtol(argv[1], &endPtr1, 10); // Convert the first argument
long num2 = strtol(argv[2], &endPtr2, 10); // Convert the second argument
if (*endPtr1 != '\0' || *endPtr2 != '\0') // Verify that both inputs are valid integers
{
printf("Invalid numeric input.\n"); // Print an error message
return 1; // Exit with an error code
}
printf("Product = %ld\n", num1 * num2); // Display the product
return 0; // End the program
}Common Mistakes and Pitfalls
| Wrong | Correct |
|---|---|
| Accessing argv[1] without checking argc | Verify argc before accessing arguments |
| Assuming arguments are integers | Convert strings using strtol() or atoi() |
| Using atoi() without validation | Prefer strtol() for better error handling |
| Forgetting that argv[0] contains the program name | Start user arguments from argv[1] |
| Ignoring invalid input | Validate converted values before using them |
Wrong:
printf("%s\n", argv[1]);Correct:
if (argc > 1)
{
printf("%s\n", argv[1]);
}
else
{
printf("No argument provided.\n");
}Best Practices
- Always verify the value of argc before accessing argv.
- Display clear usage instructions when arguments are missing or incorrect.
- Use strtol() or strtod() instead of atoi() or atof() for reliable error checking.
- Validate user input before processing it.
- Use descriptive argument names in documentation and help messages.
- Handle invalid file names and numeric values gracefully.
When NOT to Use This
Avoid command line arguments when:
- The program requires continuous interactive input.
- A graphical user interface (GUI) is more appropriate.
- Sensitive information such as passwords should not appear in the command line, since command-line arguments may be visible to other users or recorded in shell history.
- Configuration files or environment variables provide a better solution for large sets of options.
Summary / Key Takeaways
- Command Line Arguments in C programming allow input to be passed when a program starts.
- The main() function can accept arguments using int main(int argc, char *argv[]).
- argc stores the number of command line arguments.
- argv is an array of strings containing those arguments.
- argv[0] is the program name.
- Numeric arguments must be converted from strings before use.
- Always validate the number and format of command line arguments.
- Command line arguments are useful for automation, scripting, and file processing.
FAQ About Command Line Arguments in C
1. What are command line arguments in C?
Command line arguments are values passed to a program when it starts executing. They allow users to provide input without using functions such as scanf().
2. What is argc?
argc (Argument Count) stores the total number of command line arguments, including the program name.
3. What is argv?
argv (Argument Vector) is an array of strings that stores all command line arguments. Each element points to one argument.
4. Why is argv[0] the program name?
By convention, the operating system passes the program's name or the path used to invoke it as the first command line argument, allowing the program to identify how it was started.
5. Should I use atoi() or strtol()?
For simple examples, atoi() is easy to use. However, for real-world applications, strtol() is recommended because it provides better error detection and lets you distinguish between invalid input and valid numeric values.