What are argc and argv?
Up until now you have written int main(void), but main can also be written to accept arguments.
int main(int argc, char *argv[]) {
// argc: number of arguments (Argument Count)
// argv: array of argument strings (Argument Vector)
}
argc
Number of arguments (including the program name)
argv[]
Each argument as a string (array of char*)
For example, running ./myprogram hello world:
| Variable | Value | Meaning |
| argc | 3 | 3 arguments |
| argv[0] | "./myprogram" | program name |
| argv[1] | "hello" | 1st argument |
| argv[2] | "world" | 2nd argument |
Important: argv[0] is the program's own name. User-supplied arguments start from argv[1].
Basic Usage
A program that prints all arguments:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
$ gcc args.c -o args
$ ./args hello world 123
Number of arguments: 4
argv[0] = ./args
argv[1] = hello
argv[2] = world
argv[3] = 123
Using Arguments as Numbers
Every element of argv is a string (char*). To use one as a number, you must convert it.
| Function | Target type | Header | Example |
atoi(s) | int | stdlib.h | int n = atoi(argv[1]); |
atof(s) | double | stdlib.h | double d = atof(argv[1]); |
atol(s) | long | stdlib.h | long l = atol(argv[1]); |
Example: command-line calculator
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s num1 num2\n", argv[0]);
return 1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("%d + %d = %d\n", a, b, a + b);
return 0;
}
$ ./calc 15 27
15 + 27 = 42
Validating arguments is essential. Check argc and if there are not enough arguments, print usage and exit.
Practical Example: Passing a File Name
Real programs often take the name of the file to process as a command-line argument.
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s filename\n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Cannot open file '%s'\n", argv[1]);
return 1;
}
char line[256];
while (fgets(line, 256, fp) != NULL) {
printf("%s", line);
}
fclose(fp);
return 0;
}
$ ./cat scores.txt
Taro 80
Hanako 95
Jiro 70
This is a simplified version of the UNIX cat command.
Quiz
// When you run the following command
// $ ./prog hello world
What is the value of argc?
2
3
1
0
Explanation: argc counts the arguments including the program name: ./prog, hello, world = 3.
argv[0]="./prog", argv[1]="hello", argv[2]="world".
// Running $ ./calc 10 20
int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("%d\n", a + b);
What does it print?
30
1020
error
0
Explanation: atoi("10") → 10, atoi("20") → 20. 10 + 20 = 30.
Without atoi you would get string concatenation ("1020"), so be careful.