A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
main is not required to take zero parameters. The standard defines two valid signatures: int main(void) and int main(int argc, char *argv[]). The second form gives you access to whatever the user typed after the program name. argc is the count. argv is an array of C strings. argv[0] is the program name itself. argv[argc] is guaranteed to be NULL. These are your program's first contact with the outside world.
#include <stdio.h>int main(int argc, char *argv[]) {printf("Program name: %s\n", argv[0]);printf("Argument count: %d\n", argc);for (int i = 1; i < argc; i++) {printf("argv[%d] = \"%s\"\n", i, argv[i]);}return 0;}
Quoted strings in the shell become a single argv entry. "two words" is one argument, not two. The shell handles the parsing before your program ever sees it. Your program receives the already-split array. Every argument is a string. If you need an integer, you convert it with atoi or strtol. There is no type information. It is all text.
#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]) {if (argc != 3) {fprintf(stderr, "Usage: %s <filename> <count>\n", argv[0]);return 1;}const char *filename = argv[1];char *endptr;long count = strtol(argv[2], &endptr, 10);if (*endptr != '\0' || count <= 0) {fprintf(stderr, "Error: count must be a positive integer\n");return 1;}printf("File: %s, Count: %ld\n", filename, count);return 0;}
strtol is preferred over atoi because it reports conversion errors via the endptr. atoi returns 0 on failure, which is indistinguishable from a legitimate input of "0". strtol lets you check whether the entire string was consumed. The usage message on stderr follows Unix convention: show the user what they should have typed, and exit with a nonzero status.
Command-line arguments are the simplest interface between a user and your program. Every Unix tool, every build script, every cron job passes arguments. Getting the parsing right, with proper validation and usage messages, is the difference between a tool people trust and one they curse. Next: remove, for deleting files from within C.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.