Command-Line Arguments
Understanding Command-Line Arguments
Command-line arguments allow users to pass information to a program directly from the terminal when executing it. They provide a flexible way to interact with programs without modifying the source code.
Basic Argument Structure
int main(int argc, char *argv[]) {
// argc: Argument Count
// argv: Argument Vector
return 0;
}
Argument Components
Component |
Description |
Example |
argc |
Total number of arguments |
3 in ./program arg1 arg2 |
argv[0] |
Program name |
./program |
argv[1] |
First argument |
arg1 |
argv[n] |
Subsequent arguments |
arg2 , arg3 , etc. |
Practical Example
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Program Name: %s\n", argv[0]);
printf("Total Arguments: %d\n", argc);
for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Argument Processing Workflow
graph TD
A[Execute Program] --> B[Shell Passes Arguments]
B --> C[main() Receives argc/argv]
C --> D[Process Arguments]
D --> E[Program Execution]
Advanced Argument Handling
Argument Type Conversion
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
int number = atoi(argv[1]); // Convert string to integer
printf("Converted Number: %d\n", number);
}
return 0;
}
Common Use Cases
- File processing
- Configuration settings
- Input parameters
- Program customization
Ubuntu 22.04 Demonstration
## Compile the program
gcc -o argdemo argdemo.c
## Run with arguments
./argdemo Hello LabEx
Best Practices
- Always validate argument count
- Handle potential conversion errors
- Provide usage instructions
- Use getopt() for complex argument parsing
LabEx Tip
In LabEx C programming environments, mastering command-line arguments enables more dynamic and interactive program designs.