C Command Line Arguments Explained: argc, argv, and Program Input
Command line arguments allow users to provide information to a C program when starting it from a terminal. They are useful for filenames, configuration options, numbers, modes, and other runtime parameters.
What are Command Line Arguments?
Command line arguments are values written after the program name when launching an executable. In C, they are received by the main function through argc and argv.
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Argument count: %d\n", argc);
return 0;
}
Understanding argc
argc stands for argument count. It contains the number of command line arguments passed to the program, including the program name itself.
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Number of arguments: %d\n", argc);
return 0;
}
Understanding argv
argv is an array of pointers to strings. Each element contains one command line argument.
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 0; i < argc; i++)
{
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
Example Command
Suppose the compiled program is called app. Running it with several arguments could look like this:
./app Alice 25 Developer
The program name is normally available as argv[0], while the additional arguments begin at argv[1].
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 4)
{
printf("Usage: %s <name> <age> <job>\n", argv[0]);
return 1;
}
printf("Name: %s\n", argv[1]);
printf("Age: %s\n", argv[2]);
printf("Job: %s\n", argv[3]);
return 0;
}
argc and argv Relationship
| Element | Meaning | Example |
|---|---|---|
| argc | Number of arguments | 4 |
| argv[0] | Program name | ./app |
| argv[1] | First user argument | Alice |
| argv[2] | Second user argument | 25 |
| argv[3] | Third user argument | Developer |
Checking the Number of Arguments
Before accessing a particular argv element, check argc to make sure the argument exists.
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Please provide a name.\n");
return 1;
}
printf("Hello, %s!\n", argv[1]);
return 0;
}
Converting Arguments to Integers
Command line arguments are strings. When numeric input is required, the string must be converted to an appropriate numeric type.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: %s <number>\n", argv[0]);
return 1;
}
int number = atoi(argv[1]);
printf("Number: %d\n", number);
return 0;
}
Using strtol for Safer Conversion
For more reliable integer parsing, strtol provides better error detection than atoi because it allows the program to inspect whether conversion succeeded completely.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: %s <number>\n", argv[0]);
return 1;
}
char *end;
errno = 0;
long value = strtol(argv[1], &end, 10);
if (errno == ERANGE || *end != '\0' || value < INT_MIN || value > INT_MAX)
{
printf("Invalid integer: %s\n", argv[1]);
return 1;
}
printf("Value: %ld\n", value);
return 0;
}
Building a Simple Calculator
Command line arguments can be used to create small utilities that receive their operands directly from the terminal.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 3)
{
printf("Usage: %s <a> <b>\n", argv[0]);
return 1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("Sum: %d\n", a + b);
return 0;
}
Using Command Line Options
Arguments can represent options such as modes or features. A program can compare argument strings and select the required behavior.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: %s --verbose\n", argv[0]);
return 1;
}
if (strcmp(argv[1], "--verbose") == 0)
{
printf("Verbose mode enabled\n");
}
else
{
printf("Unknown option: %s\n", argv[1]);
}
return 0;
}
Processing Multiple Arguments
A loop can process an arbitrary number of command line arguments, which is useful for tools that accept lists of files or values.
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++)
{
printf("Input %d: %s\n", i, argv[i]);
}
return 0;
}
Command Line Arguments and File Handling
A common pattern is accepting a filename from the command line and then opening it using standard file handling functions.
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: %s <file>\n", argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
perror(argv[1]);
return 1;
}
char line[256];
while (fgets(line, sizeof line, file) != NULL)
{
printf("%s", line);
}
fclose(file);
return 0;
}
Arguments with Spaces
The shell normally separates command line arguments at whitespace. Quoting an argument allows a value containing spaces to be passed as one argument.
./app "John Smith" "Software Developer"
Command Line Arguments vs Standard Input
| Feature | Command Line Arguments | Standard Input |
|---|---|---|
| Input Time | Provided when launching the program | Usually provided while the program runs |
| Access | argc and argv | scanf, fgets, getchar, etc. |
| Common Use | Options, filenames, configuration | Interactive user input |
Common Mistakes to Avoid
- Accessing argv elements without checking argc
- Assuming every argument is numeric
- Using atoi when detailed conversion errors matter
- Ignoring unknown command line options
- Forgetting that argv values are strings
- Assuming arguments containing spaces are automatically kept together
Command Line Best Practices
- Validate the number of arguments
- Validate argument contents before using them
- Provide a clear usage message
- Use robust numeric conversion when necessary
- Handle unknown options gracefully
- Keep command line syntax simple and predictable
Real-World Applications
- File processing utilities
- Build tools
- System administration programs
- Backup utilities
- Data conversion tools
- Compiler and development tools
- Command-line automation scripts
Practice Exercises
- Create a program that prints all command line arguments
- Build a command-line calculator
- Accept a filename and display its contents
- Create a program with --help and --version options
- Convert a command line string into an integer safely
- Count how many arguments were provided
- Build a simple command-line file search utility
Conclusion
Command line arguments provide a simple and powerful way to pass information to C programs at startup. By understanding argc, argv, argument validation, string processing, and numeric conversion, you can build flexible command-line applications.