Module 8 · Files, the Preprocessor and Program Organisation — topic 4 of 4
Command-Line Arguments
main can receive the words typed after the program name. Learn argc and argv, converting arguments to numbers safely with strtol, and writing proper usage messages and exit codes.
Learning objectives
- Read argc and argv in main
- Convert argument strings to numbers with error checking
- Return meaningful exit codes and print usage messages
Definition
In a hosted environment,mainmay be declared asint main(int argc, char *argv[]), whereargcis the number of arguments andargvis an array ofargcstrings —argv[0]is the program name — terminated byargv[argc] == NULL.
Introduction
Command-line tools such as gcc hello.c -o hello take their input from arguments rather than interactive prompts. That makes them scriptable: they can be run from other programs, build systems and batch files.
Your C programs can work the same way. The operating system passes the words of the command to main as an array of strings.
Why it matters
Projects like a mini shell, file encryption tool and file compression utility take file names and options from the command line.
Exit codes (return 0 for success, non-zero for failure) let scripts and build tools react to your program's result.
Detailed explanation
For the command ./calc 12 + 30, argc is 4 and argv is {"./calc", "12", "+", "30", NULL}.
Every argument is a string. Convert numbers with strtol (integers) or strtod (floating point). Unlike atoi, strtol reports errors: check that it consumed the whole string and that errno is not ERANGE.
Check argc before reading argv[i]; reading past argc is undefined behaviour (argv[argc] itself is NULL).
Print a usage message to stderr (fprintf(stderr, ...)) when arguments are wrong, and return a non-zero status such as EXIT_FAILURE from <stdlib.h>.
Arguments containing spaces must be quoted by the user: ./greet "Asha Rao" arrives as one argument.
Syntax
char **argvis equivalent tochar *argv[]in a parameter.EXIT_SUCCESS(0) andEXIT_FAILUREcome from<stdlib.h>.- Run with arguments:
./prog 5 10.
Code examples
Listing the arguments
argc = 1 no arguments given
Run as ./args red green to see argc = 3 and both words.
Running with arguments
More examples
A safe argument-driven calculator
360 status 0 error: operands must be whole numbers status 1 usage: calc A OP B (OP is + - x /) status 1
Step-by-step explanation
runtakesargc/argvexactly likemain, so it can be tested with simulated command lines; a real program would callreturn run(argc, argv);frommain.parse_longrejects empty input (end == s), trailing junk such as the letter O in "3O" (*end != '\0') and out-of-range values (ERANGE).argv[2][0]is the first character of the operator argument.xis used for multiplication because the shell expands*into file names.- Each error path prints a message and returns
EXIT_FAILURE(1), which scripts can detect.
Expected output
Running “A safe argument-driven calculator” prints exactly:
Practical applications
- Compilers,
git,lsandpingare controlled entirely through arguments. - Build scripts check exit codes to stop when a step fails.
- Utilities such as
grep pattern fileread options and file names from argv.
Best practices
- Validate the number and format of arguments first and print a usage line.
- Use
strtol/strtodfor numeric arguments. - Return
EXIT_SUCCESS/EXIT_FAILUREso callers can check the result.
Common mistakes
Reading argv without checking argc
Avoid
Prefer
With no arguments, argv[1] is NULL; printing it is undefined behaviour.
Using atoi without validation
Avoid
Prefer
atoi cannot report errors; strtol tells you where parsing stopped.
Important notes
- The strings in
argvbelong to the program and may be modified, but it is clearer to copy them before changing them. - Option-parsing libraries such as POSIX
getopthandle flags like-vand--output filefor larger tools.
Key takeaways
argccounts arguments;argv[0]is the program name.- All arguments are strings — convert with
strtoland check errors. - Print usage and return a non-zero status on bad input.
Try it yourself
- 1Write
./sum 4 8 15 16that prints the total of all numeric arguments and rejects invalid ones. - 2Write a tool
./upper file.txtthat prints a file in capital letters, with a usage message when the file name is missing.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
3 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerFor the command `./app one two`, what is the value of argc?
- ModerateWhy is `strtol` preferred over `atoi` for parsing a numeric argument?
- AdvancedWhat is guaranteed about `argv[argc]`?