CS210 · Block 3 · Lesson 22

Command-Line Arguments and the Outside Environment

argc · argv · Argument validation · Exit status · Environment variables
At a glance: Every C program you have written so far has been a closed box. Today the outside world starts talking to your code in three places: at launch through argc and argv, at termination through the return value of main, and through the shell with environment variables. Heads up: today is also Quiz 8 (File I/O) and the Team PEX is assigned.
Contents
  1. Lesson Objectives
  2. Assigned Readings
  3. Pre-Class Work
  4. Lesson Materials and Overview
  5. In-Class Work
  6. After Class
1. Lesson Objectives

By the end of this lesson, cadets will be able to:

  1. Access command-line arguments through argc and argv. (Outcome 2)
  2. Parse and validate command-line input in a C program. (Outcome 3)
  3. Use main's return value to communicate program status to the calling shell. (Outcomes 2, 7)
  4. Read environment variables with getenv to let the runtime environment configure program behavior. (Outcomes 2, 7)
2. Assigned Readings

Complete before class. These set the vocabulary we will use.

Source Sections Why
Beej-C Chapter 18 (The Outside Environment) argc, argv, exit status, environment variables
3. Pre-Class Work
Do this first
Plan on 25 to 35 minutes. Today is a lean content day because Quiz 8 (File I/O) is also today; come ready to write a small command-line program quickly.

Pre-Class Checklist

1
Read Beej-C Chapter 18
Beej covers the three things on the menu today: argc and argv (Section 18.1), exit status (18.2), and environment variables (18.3). Skim Section 18.1.2 (the char **argv alternate notation) for now; we will revisit the equivalence in slides.
2
Predict the output before reading the answer
Suppose you compile and run:
$ ./prog "one two" three 4
What is argc? What is each cell of argv (including the sentinel at the end)? Try the in-class walkthrough widget to confirm.
Click for the answer
argc is 4. argv[0]="./prog", argv[1]="one two" (the quotes group those two words into one argument), argv[2]="three", argv[3]="4" (a string, not a number), and argv[4]=NULL.
3
Skim the In-Class section below
Two widgets today: a guided walkthrough through argv, exit status, and getenv, and a self-check quiz. The lab is a Strava-style activity log filter that pulls all three together.
4. Lesson Materials and Overview

Three ways the world talks to your program. Read each subsection below; the slides cover the same material at the front of class, and the walkthrough widget gives you hands-on practice with each one.

Jump to
Slides Shape of argv Parsing and Validating Exit Status Environment Variables Where this goes next: getopt

Slides

The Lesson 22 deck covers argv shape, parsing and validating, exit status, environment variables, and a brief glance at getopt as the standard idiom you will meet again in CS220.

Open Lesson 22 slides →

The shape of argv

When the shell launches your program, it hands main two parameters. The signature changes from the int main(void) you have been writing to:

int main(int argc, char *argv[]) {
  // argc = how many arguments, including the program name
  // argv[0] = program name as the shell invoked it
  // argv[1] .. argv[argc-1] = user-supplied arguments
  // argv[argc] = NULL (guaranteed by the C standard)
  return 0;
}

If you run ./prog hello 42, then argc is 3 (the program name counts) and argv looks like this:

Index Value (a string)
argv[0] "./prog"
argv[1] "hello"
argv[2] "42" // still a string, not a number
argv[3] NULL // sentinel; guaranteed by the standard

Quoting groups: ./prog "hello world" 5 gives argc=3, not argc=4. The shell sees the double quotes and packs the whole phrase into one argv cell.

Parsing and validating

argv elements are strings. To use them as numbers, you convert:

// Quick conversion, no error reporting
int n = atoi(argv[1]);
double d = atof(argv[2]);

The trap: atoi returns 0 for both "0" and "banana". There is no error flag. For inputs you cannot trust, strtol reports parse failures through an end-pointer and errno. For CS210 labs, atoi is usually fine; the lab spec will tell you when validation is part of the grade.

Validate before you index. Always check argc before reading from argv. The pattern:

if (argc < 3) {
  fprintf(stderr, "usage: %s <file> <threshold>\n", argv[0]);
  return EXIT_FAILURE;
}

Usage messages and errors go to stderr, not stdout. The reason: if your program is piped to another (./prog file.txt | sort), stdout becomes the next program's input. Errors on stdout would corrupt the data; errors on stderr still land on the terminal where the user can see them.

Exit status

The integer your main returns is captured by the shell as the program's exit status. Zero means success; any non-zero value means failure. The <stdlib.h> macros make the intent obvious:

return EXIT_SUCCESS;  // same as return 0;
return EXIT_FAILURE;  // 1 on every Unix you'll meet

After your program ends, the shell exposes the exit code as $?:

$ ./prog file.txt
$ echo $?
0
$ ./prog
usage: ./prog <file> <threshold>
$ echo $?
1

Environment variables

Beyond what gets passed at launch, the shell also gives your program a set of environment variables: key-value pairs like USER=cadet22 and HOME=/home/cadet22 that any process inherits. You read them with getenv:

char *user = getenv("USER");
if (user == NULL) {
  fprintf(stderr, "USER not set\n");
} else {
  printf("hello, %s\n", user);
}

getenv returns a pointer to the value string, or NULL if the variable is not set. Always check for NULL before using the result. The returned string belongs to the environment, not to you, so do not free it and do not modify it.

Why this matters: environment variables let you change your program's behavior without recompiling. The lab uses STRAVA_QUIET as a small example: when set, the filter suppresses its summary line.

Where this goes next: getopt

Real Unix command-line tools (grep -i pattern file, gcc -Wall -Werror file.c, ls -la) accept option flags in standard shapes. The standard library function that recognizes these patterns is getopt. A taste:

// recognize -v (verbose flag) and -n NUM (option with value)
int c;
while ((c = getopt(argc, argv, "vn:")) != -1) {
  switch (c) {
    case 'v': verbose = 1; break;
    case 'n': n = atoi(optarg); break;
  }
}

You will not write getopt in CS210; the lab uses simple positional arguments. But you will see this idiom in any real command-line tool you read, and in CS220.

5. In-Class Work

Four things to do in class. Use the checklist to track your progress.

  • Quiz 8: File I/O. Closed-resource, about 15 minutes. Covers Lesson 21 content (fopen/fclose, fscanf, sscanf, error handling). Your instructor will tell you when to take it.
  • Work through the argv walkthrough below. Twelve guided tasks covering argv shape, indexing, exit status, and environment variables. About 25 minutes.
  • Take the argv self-check. Eight questions covering argc/argv mechanics, the NULL sentinel, atoi traps, exit status, and getenv. About 10 minutes.
  • Complete Lab 22: Strava Activity Filter. Auto-graded through GitHub Classroom. Full instructions in the lab repo.

argv Walkthrough

Twelve tasks across four sections. Type each shell invocation or C call at the prompt. The terminal shows what happened; the right pane shows the current argv array, exit status, and any environment variables you read.

Before you begin

Enter your name. It will appear on the completion screen so you can include it in your screenshot for the Lesson 22 reflection.

CS210 Lesson 22 · argv Walkthrough

A guided tour through command-line arguments, exit status, and environment variables. Type each invocation or C statement at the prompt. The terminal shows what happened; the right pane shows the current argv array, exit status, and any environment variables you read.
Task 0 of 12
Section 1: The shape of argv
Current task
Loading...
Program State
No invocation yet.
Type a fake command on the left.
$
How this works: This widget simulates a shell launching a C program. Type a fake invocation like ./prog hello 42 and watch the resulting argv array appear. Some tasks ask you to type a C statement instead (like atoi(argv[1])) to see what would happen inside main. Only the expected input will advance the walkthrough. Mistype twice and the hint button will pulse. Free mode unlocks at the end.

argv Self-Check Quiz

Eight questions. Pass at 70% or above; below that, take it again after reviewing the materials and replaying the walkthrough.

Before you begin

Enter your name. It will appear on the score card so you can include it in your screenshot for the Lesson 22 reflection.

CS210 Lesson 22 · argv Self-Check

Eight questions covering argc, argv, the NULL sentinel, atoi traps, exit status, and getenv. Pass at 70% or above; below that, take it again after reviewing.
How this works: One question per card. Pick or type your answer and click Submit. Feedback appears, then click Next to move on. Answers lock once submitted, so think before you submit. After all eight, you get a score, a completion code, and a per-question recap.
6. After Class
  • Finish Lab 22 if you did not complete it in class. Submit through GitHub Classroom before Lesson 23.
  • Submit the Lesson 22 reflection in Blackboard. Include the completion codes from both widgets and your screenshot.
  • Team PEX was assigned today. Review the topic list and start thinking about which one fits your team's interests. Topic proposal is due at Lesson 23; the full PEX is due at Lesson 39.
  • Read the supplementary notes for Lesson 23 (Software Design from Requirements) before next class.
  • Heads up: GR3 at Lesson 28 covers Block 3 content. argv, exit status, and getenv are fair game.
Need help? Schedule EI with your instructor. Bring specific code or specific terminal output, and the exact error message or behavior you do not understand. Specific questions get unstuck quickly.