Command line arguments let users pass data to a C program at the moment they run it — without embedding values in the source code or prompting for input. When you run ./copy src.txt dst.txt, the strings src.txt and dst.txt arrive in your program through two special parameters: argc and argv. Understanding them is essential for writing reusable command-line tools in C.
argc and argv Explained
| Parameter | Type | What it holds |
|---|---|---|
argc |
int |
Count of arguments, including the program name — always ≥ 1 |
argv |
char *[] |
Array of C strings; argv[0] is the program name, argv[1]–argv[argc-1] are the user’s arguments, argv[argc] is NULL |
Example: running ./cmdargs hello 42 gives argc = 3 and:
argv[0] = "./cmdargs" argv[1] = "hello" argv[2] = "42" argv[3] = NULL
C Program for Command Line Arguments
/* Command line arguments in C — argc and argv
* Compile: gcc -ansi -Wall -Wextra cmdargs.c -o cmdargs
* Run: ./cmdargs hello world 42 */
#include <stdio.h>
#include <stdlib.h> /* atoi, atof */
int main(int argc, char *argv[])
{
int i;
printf("Program name : %s\n", argv[0]);
printf("Argument count: %d (including program name)\n", argc);
if (argc == 1) {
printf("No arguments passed.\n");
printf("Usage: %s arg1 arg2 ...\n", argv[0]);
return 0;
}
printf("\nArguments received:\n");
for (i = 1; i < argc; i++)
printf(" argv[%d] = \"%s\"\n", i, argv[i]);
/* demonstrate converting a string argument to a number */
if (argc >= 2) {
printf("\nFirst argument as integer: %d\n", atoi(argv[1]));
printf("First argument as float : %.4f\n", atof(argv[1]));
}
return 0;
}
How to Compile and Run
gcc -ansi -Wall -Wextra cmdargs.c -o cmdargs
./cmdargs # no arguments
./cmdargs hello 42 world
./cmdargs 3.14
Sample Output
# Run with no arguments: Program name : ./cmdargs Argument count: 1 (including program name) No arguments passed. Usage: ./cmdargs arg1 arg2 ... # Run as: ./cmdargs hello 42 world Program name : ./cmdargs Argument count: 4 (including program name) Arguments received: argv[1] = "hello" argv[2] = "42" argv[3] = "world" First argument as integer: 0 First argument as float : 0.0000 # Run as: ./cmdargs 3.14 Program name : ./cmdargs Argument count: 2 (including program name) Arguments received: argv[1] = "3.14" First argument as integer: 3 First argument as float : 3.1400
Note: atoi("hello") returns 0 — it does not crash. Any non-numeric prefix returns 0. atoi("3.14") returns 3 (integer truncation). For robust parsing, prefer strtol() or strtod() which report conversion errors via a pointer.
Code Explanation
int main(int argc, char *argv[])— this is the correct C89 signature for a main function that receives arguments. The two parameters can be named anything (conventionally argc/argv), but the types must beintandchar **(equivalentlychar *[]). The compiler sees both as identical.argv[0]is always the program name — it contains the path used to invoke the program (e.g.,./cmdargsor/usr/local/bin/cmdargs). That is whyargcis always at least 1 even with no user arguments.- The loop starts at
i = 1— skippingargv[0](the program name) to iterate only over user-supplied arguments. Usingi < argc(noti <= argc) avoids reading the NULL sentinel atargv[argc]. atoi()andatof()from<stdlib.h>— convert a string argument to an integer or floating-point number. They work on the string pointed to byargv[i]directly. Passing a non-numeric string returns 0 without error, which is convenient but can hide bugs. For error detection:strtol(argv[1], &end, 10)— ifend == argv[1], no conversion happened.- Returning 0 on early exit — when no arguments are passed, the program prints usage help and exits with 0 (success). An exit code of 1 would signal an error to the calling shell.
How the Shell Passes Arguments
The shell splits the command line on whitespace and passes each token as a separate string. Quoting changes this:
./cmdargs hello world # argc=3: "hello", "world" ./cmdargs "hello world" # argc=2: "hello world" (one argument) ./cmdargs hello\ world # argc=2: "hello world" (backslash escape) ./cmdargs $HOME # argc=2: "/Users/you" (shell expands $HOME first)
Practical Uses
- File operations:
./copy source.txt dest.txt— read two filenames from argv - Configuration flags:
./server -p 8080 -v— scan argv for-p, read the next token as port number - Batch processing:
./process *.txt— the shell glob expands to multiple argv entries - Tool chaining: command line tools like
grep,sort,wcall use argc/argv — every Unix utility is built on this interface
What This Program Teaches
- The full main() signature —
int main(int argc, char *argv[])is the standard entry point for programs that need to receive input from the shell.int main(void)is valid when no arguments are needed. - argv as a pointer to an array of strings — each
argv[i]is achar *, a pointer to a null-terminated string. The array itself is terminated by a NULL pointer atargv[argc]. - String-to-number conversion — all command-line data arrives as strings. Converting to int/float requires explicit calls to
atoi(),atof(),strtol(), orsscanf(). - Usage messages — when a program receives too few or invalid arguments, printing
Usage: argv[0] ...is the Unix convention. Usingargv[0]instead of the hard-coded program name means the message stays correct if the binary is renamed.
Related Programs
Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
|
C Programming: A Modern Approach — K.N. King (India) |
(US)
Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.