How to Parse Command Line Arguments in C: Simple Guide
In C, command line arguments are parsed using the
argc and argv parameters of the main function. argc tells how many arguments were passed, and argv is an array of strings holding each argument.Syntax
The main function can accept two parameters: int argc and char *argv[]. Here:
- argc is the count of command line arguments including the program name.
- argv is an array of strings where each element is one argument.
This lets your program read inputs given when it starts.
c
int main(int argc, char *argv[]) { // Your code here return 0; }
Example
This example prints all command line arguments passed to the program, including the program name itself.
c
#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; }
Output
Number of arguments: 3
Argument 0: ./program
Argument 1: hello
Argument 2: world
Common Pitfalls
Common mistakes when parsing command line arguments include:
- Not checking if
argcis large enough before accessingargvelements, which can cause crashes. - Assuming arguments are always in a fixed order without validation.
- Confusing
argv[0](program name) with user inputs.
Always validate argc before using argv to avoid errors.
c
#include <stdio.h> int main(int argc, char *argv[]) { // Wrong: Accessing argv[1] without checking argc // printf("First argument: %s\n", argv[1]); // May crash if no argument given // Right: Check argc first if (argc > 1) { printf("First argument: %s\n", argv[1]); } else { printf("No arguments provided.\n"); } return 0; }
Output
No arguments provided.
Quick Reference
Remember these tips when parsing command line arguments in C:
- argc counts all arguments including program name.
- argv[0] is the program name.
- Check
argcbefore accessingargvelements. - Arguments are strings; convert them if needed (e.g.,
atoifor numbers).
Key Takeaways
Use
int argc, char *argv[] in main to access command line arguments.Always check
argc before using argv to avoid errors.argv[0] holds the program name, not user input.Arguments are strings; convert them to other types as needed.
Loop through
argv to process all arguments.