Command Line Arguments in C
Learn to pass data to your programs when running them! Master argc and argv, parse command line flags, and build powerful CLI tools.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Understand what command line arguments are
- ✓Use argc (argument count) and argv (argument vector)
- ✓Convert string arguments to numbers with atoi/atof
- ✓Validate and handle missing or invalid arguments
- ✓Parse command line flags and options
- ✓Build practical CLI tools
?Why Use Command Line Arguments?
Without command line arguments, your program must ask for input interactively. But what if you want to:
Automate Tasks
Run your program in scripts without manual input:./process file1.txt file2.txt
⚙️ Configure Behavior
Change program behavior with flags:./program --verbose --output=result.txt
Build CLI Tools
Create professional tools like gcc, ls, git
Batch Processing
Process multiple files in a loop without recompiling
01What are Command Line Arguments?
Command line arguments allow you to pass data to your program when you run it from the terminal. Instead of asking for input during execution, users can provide values directly when starting the program.
Example Usage
# Without command line arguments
./program
# With command line arguments
./program hello world 123
Real-World Examples
- •
gcc myfile.c -o myprogram— compiler takes file names as arguments - •
ls -la /home— flags and paths as arguments - •
cp source.txt dest.txt— copy command takes file names
02Understanding argc and argv
To receive command line arguments, your main() function must use two special parameters:
Memory Visualization: argv Array
Command: ./calc add 5 10
argv[argc] is always NULL — marks end of array
argc (Argument Count)
An int that holds the number of arguments passed, including the program name itself.
./program hello world
argc = 3
argv (Argument Vector)
An array of char* (strings) containing each argument.
./program hello world
argv[0] = "./program"
argv[1] = "hello"
argv[2] = "world"
1// Standard main() without arguments2int main(void) {3 return 0;4}56// main() with command line arguments7int main(int argc, char *argv[]) {8 // argc = argument count9 // argv = argument vector (array of strings)10 return 0;11}1213// Alternative syntax (equivalent)14int main(int argc, char **argv) {15 return 0;16}03Your First Command Line Program
Let's create a simple program that prints all the arguments passed to it:
1#include <stdio.h>23int main(int argc, char *argv[]) {4 printf("Number of arguments: %d\n", argc);5 6 printf("\nAll arguments:\n");7 for (int i = 0; i < argc; i++) {8 printf(" argv[%d] = %s\n", i, argv[i]);9 }10 11 return 0;12}Output
$ ./print_args hello world 123
Number of arguments: 4
All arguments:
argv[0] = ./print_args
argv[1] = hello
argv[2] = world
argv[3] = 123
Important Notes
- •
argv[0]is always the program name - • All arguments are strings, even numbers like "123"
- •
argv[argc]is guaranteed to be NULL
04Converting String Arguments to Numbers
Since all command line arguments are strings, you need to convert them if you want to use them as numbers.
| Function | Header | Converts to | Example |
|---|---|---|---|
| atoi() | <stdlib.h> | int | atoi("123") → 123 |
| atol() | <stdlib.h> | long | atol("123456") → 123456L |
| atof() | <stdlib.h> | double | atof("3.14") → 3.14 |
| strtol() | <stdlib.h> | long | Better error handling |
1#include <stdio.h>2#include <stdlib.h> // For atoi()34int main(int argc, char *argv[]) {5 // Check if correct number of arguments6 if (argc != 4) {7 printf("Usage: %s <num1> <operator> <num2>\n", argv[0]);8 printf("Example: %s 10 + 5\n", argv[0]);9 return 1;10 }11 12 // Convert string arguments to numbers13 int num1 = atoi(argv[1]);14 char operator = argv[2][0]; // First character of operator string15 int num2 = atoi(argv[3]);16 17 int result;18 19 switch (operator) {20 case '+': result = num1 + num2; break;21 case '-': result = num1 - num2; break;22 case 'x': result = num1 * num2; break; // Use 'x' for multiply23 case '/': 24 if (num2 == 0) {25 printf("Error: Division by zero!\n");26 return 1;27 }28 result = num1 / num2; 29 break;30 default:31 printf("Unknown operator: %c\n", operator);32 return 1;33 }34 35 printf("%d %c %d = %d\n", num1, operator, num2, result);36 return 0;37}Output
$ ./calculator 10 + 5
10 + 5 = 15
$ ./calculator 20 - 8
20 - 8 = 12
$ ./calculator 6 x 7
6 x 7 = 42
05Validating Command Line Arguments
Always validate command line arguments! Users might provide wrong inputs, missing arguments, or invalid data.
1#include <stdio.h>2#include <stdlib.h>34int main(int argc, char *argv[]) {5 // Step 1: Check argument count6 if (argc < 2) {7 fprintf(stderr, "Error: No filename provided\n");8 fprintf(stderr, "Usage: %s <filename>\n", argv[0]);9 return 1;10 }11 12 // Step 2: Try to open the file13 FILE *file = fopen(argv[1], "r");14 if (file == NULL) {15 fprintf(stderr, "Error: Cannot open file '%s'\n", argv[1]);16 return 1;17 }18 19 // Step 3: Read and display file contents20 printf("Contents of %s:\n", argv[1]);21 printf("─────────────────────────\n");22 23 char buffer[256];24 while (fgets(buffer, sizeof(buffer), file) != NULL) {25 printf("%s", buffer);26 }27 28 fclose(file);29 return 0;30}Best Practices
- ✓ Always check
argcbefore accessingargv - ✓ Provide helpful usage messages when arguments are wrong
- ✓ Use
fprintf(stderr, ...)for error messages - ✓ Return non-zero exit code on errors
06Practical Examples
Example 1: Greeting Program
1#include <stdio.h>23int main(int argc, char *argv[]) {4 if (argc == 1) {5 printf("Hello, World!\n");6 } else if (argc == 2) {7 printf("Hello, %s!\n", argv[1]);8 } else {9 printf("Hello");10 for (int i = 1; i < argc; i++) {11 printf(" %s", argv[i]);12 if (i < argc - 1) printf(",");13 }14 printf("!\n");15 }16 return 0;17}Outputs
$ ./greet → Hello, World!
$ ./greet Alice → Hello, Alice!
$ ./greet Alice Bob Carol → Hello Alice, Bob, Carol!
Example 2: File Copy Utility
1#include <stdio.h>23int main(int argc, char *argv[]) {4 if (argc != 3) {5 printf("Usage: %s <source> <destination>\n", argv[0]);6 return 1;7 }8 9 FILE *source = fopen(argv[1], "rb");10 if (!source) {11 printf("Error: Cannot open source file '%s'\n", argv[1]);12 return 1;13 }14 15 FILE *dest = fopen(argv[2], "wb");16 if (!dest) {17 printf("Error: Cannot create destination file '%s'\n", argv[2]);18 fclose(source);19 return 1;20 }21 22 char buffer[4096];23 size_t bytes;24 size_t total = 0;25 26 while ((bytes = fread(buffer, 1, sizeof(buffer), source)) > 0) {27 fwrite(buffer, 1, bytes, dest);28 total += bytes;29 }30 31 printf("Copied %zu bytes from '%s' to '%s'\n", total, argv[1], argv[2]);32 33 fclose(source);34 fclose(dest);35 return 0;36}07Processing Command Line Flags
Many programs use flags (options starting with -) to modify behavior:
1#include <stdio.h>2#include <string.h>3#include <stdbool.h>45int main(int argc, char *argv[]) {6 bool count_lines = false;7 bool count_words = false;8 bool count_chars = false;9 char *filename = NULL;10 11 // Parse command line flags12 for (int i = 1; i < argc; i++) {13 if (strcmp(argv[i], "-l") == 0) {14 count_lines = true;15 } else if (strcmp(argv[i], "-w") == 0) {16 count_words = true;17 } else if (strcmp(argv[i], "-c") == 0) {18 count_chars = true;19 } else if (argv[i][0] != '-') {20 filename = argv[i];21 }22 }23 24 // Default: count everything25 if (!count_lines && !count_words && !count_chars) {26 count_lines = count_words = count_chars = true;27 }28 29 if (!filename) {30 printf("Usage: %s [-l] [-w] [-c] <filename>\n", argv[0]);31 printf(" -l Count lines\n");32 printf(" -w Count words\n");33 printf(" -c Count characters\n");34 return 1;35 }36 37 FILE *file = fopen(filename, "r");38 if (!file) {39 printf("Error: Cannot open '%s'\n", filename);40 return 1;41 }42 43 int lines = 0, words = 0, chars = 0;44 int ch, prev = ' ';45 46 while ((ch = fgetc(file)) != EOF) {47 chars++;48 if (ch == '\n') lines++;49 if ((prev == ' ' || prev == '\n' || prev == '\t') && 50 (ch != ' ' && ch != '\n' && ch != '\t')) {51 words++;52 }53 prev = ch;54 }55 56 // Print requested counts57 if (count_lines) printf("Lines: %d\n", lines);58 if (count_words) printf("Words: %d\n", words);59 if (count_chars) printf("Chars: %d\n", chars);60 61 fclose(file);62 return 0;63}Usage Examples
$ ./wc myfile.txt # Count all
$ ./wc -l myfile.txt # Lines only
$ ./wc -w -c myfile.txt # Words and chars
!Code Pitfalls: Common Mistakes & What to Watch For
Common Mistakes with Command Line Arguments
Copying code often generate command line parsing code with dangerous flaws:
- ✗No argc validation: Beginners often access
argv[1]without checking if argc > 1, causing crashes - ✗Unsafe atoi() usage: Code often uses
atoi()without checking for non-numeric input, producing garbage values - ✗Buffer overflow risks: Beginners often copy argv strings into fixed-size buffers without length checks
- ✗Missing error messages: Beginners often forget to print usage help when arguments are wrong, confusing users
Always Understand Before Using
Test copied argument parsing with: no arguments, too many arguments, wrong types, empty strings, and special characters. Command line args are user input — never trust them! Use strtol() instead of atoi() for proper error handling.
09Frequently Asked Questions
Q:Why is argc always at least 1?
A: The program name itself counts as the first argument (argv[0]). Even running./myprogram with no args gives argc=1 and argv[0]="./myprogram". User arguments start at argv[1].
Q:How do I convert argv strings to numbers?
A: Use conversion functions:atoi(argv[1]) for int,atof(argv[1]) for float. Better: usestrtol() and strtod() which provide error checking. All arguments come as strings!
Q:What is argv[argc]?
A: It's guaranteed to be NULL by the C standard. This lets you loop with while (argv[i] != NULL) instead of checking argc. Useful for iterating all arguments.
Q:How do I handle options like -v or --help?
A: For simple cases, usestrcmp(argv[i], "-v") to check each argument. For complex options, use the getopt() function (POSIX) or getopt_long() for GNU-style long options.
Q:What happens if I use argc but declare int main(void)?
A: If you declare int main(void), argc and argv aren't available. You must useint main(int argc, char *argv[]) to access them. Both signatures are valid C; choose based on whether you need arguments.
09Summary
✓Key Points
- •
argc= argument count (including program name) - •
argv= array of string arguments - •
argv[0]= program name - • All arguments are strings — convert with
atoi(), etc. - • Always validate before using arguments
Common Uses
- • File processing tools
- • Calculators and converters
- • Automation scripts
- • Configuration utilities
- • System administration tools
11Argument Parsing Tips
Use getopt() for Complex Arguments
For programs with many options (-v, -h,--verbose), use the standard getopt()function. It handles short and long options, required values, and error reporting.
Print Usage on Error
Always provide a helpful usage message when arguments are wrong. Include the expected format, optional vs required arguments, and examples. This makes your tool user-friendly.
Support Standard Options
Consider supporting common conventions like --help and--version. These are expected by users and make your program feel professional. Return exit code 0 for success, non-zero for errors.
Test Your Knowledge
Related Tutorials
Functions in C
Organize code into reusable blocks! Functions let you write code once and use it many times. Learn to create, call, and pass data to functions.
Graphics Programming with graphics.h
Learn C graphics programming! Draw circles, ellipses, rectangles, and more using graphics.h. Covers OS/compiler support, setup instructions, and modern alternatives.
Multi-File Programs in C
Organize large projects into multiple files! Learn about header files, source files, the extern keyword, and how to compile multi-file programs.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!