Command Line Arguments in C
When a C program runs, it can receive information directly from the command line. This information is known as command line arguments.
Command line arguments allow programs to behave dynamically without changing the source code.
Why Command Line Arguments Are Useful
They are commonly used to:
- Pass filenames to a program
- Provide configuration values
- Control program behavior
- Automate tasks
Main Function with Arguments
To receive command line arguments, the main() function is written as:
int main(int argc, char *argv[])
Here:
argc→ Argument countargv→ Argument vector (array of strings)
Simple Example
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Total arguments: %d\n", argc);
for(int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
The first argument argv[0] always stores the program name.
How to Run the Program
Compile the program:
gcc args.c -o args
Run with arguments:
./args input.txt 5 debug
Real-World Example
A backup program might receive:
- Source directory
- Destination directory
- Backup mode
This avoids hard-coding paths inside the program.
Using Arguments as Numbers
Since arguments are strings, conversion is required.
#include <stdlib.h>
int value = atoi(argv[1]);
Functions like atoi, atof and strtol
are commonly used.
Quiz
Q1: What does argc represent?
Number of command line arguments
Q2: What is stored in argv[0]?
Program name
Q3: Are command line arguments strings by default?
Yes
Q4: Which function converts string to integer?
atoi()
Q5: Can we pass arguments without recompiling?
Yes
Mini Practice
- Write a program that adds two numbers from command line
- Pass a filename and display it
- Validate number of arguments using
argc