Loading
0x120Lesson 19 of 20

Make a useful command-line tool

Read arguments, report errors and return an exit status a script can use.

22 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • Explain argc and argv
  • Parse numeric text with strtol
  • Distinguish stdout, stderr and exit status

Many C programs are tools launched from a terminal or another program. The operating system passes command-line arguments to main(int argc, char *argv[]). argc counts the program name too; argv[1] is the first user argument. A good tool prints useful results to stdout, errors to stderr, and returns a nonzero status on failure.

square.c (run locally)
1#include <errno.h>
2#include <stdio.h>
3#include <stdlib.h>
4
5int main(int argc, char *argv[]) {
6    if (argc != 2) {
7        fprintf(stderr, "usage: square NUMBER\n");
8        return 2;
9    }
10    char *end;
11    errno = 0;
12    long n = strtol(argv[1], &end, 10);
13    if (errno == ERANGE || end == argv[1] || *end != '\0' || n < 0 || n > 1000) {
14        fprintf(stderr, "enter a whole number from 0 to 1000\n");
15        return 2;
16    }
17    printf("%ld\n", n * n);
18    return 0;
19}

Compile locally with gcc -std=c17 -Wall -Wextra square.c -o square, then try ./square 12, ./square 12cats, and ./square (on Windows use square.exe). atoi cannot tell you why parsing failed. strtol gives an end pointer so you can reject trailing junk, and errno reports range errors.

Try it

Up to 15 XP

Which channel?

Sort each message or result into the channel a shell script should use.

0 of 4 sortedScore 0/0
  • “The computed answer: 144”

  • “usage: square NUMBER”

  • “Return 2 when the argument is invalid”

  • “Return 0 after a successful run”

Key takeaways

  • argc and argv provide command-line text.

  • strtol plus end-pointer checks reject malformed or out-of-range numbers.

  • stdout carries results; stderr and nonzero exit status carry failures.

Lesson quiz

4 questions · pass with 3 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.

Exercise 1

Reject bad input before calculating

+25 XP

Read one line from stdin. Accept only a whole number from 0 to 1000 and print its square. For malformed input, print invalid number. Use strtol and check the end pointer; the online runner supplies stdin instead of command-line arguments.

  • Valid
  • Trailing junk
  • Out of range
main.c
Loading editor…

Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…