Lesson 01.5beginnerFoundation

Command-Line Arguments

Using argc and argv to accept command-line arguments: they arrive as strings (atoi vs strtol), options like -n 3 with a usage message, exit codes, and files named on the command line — open, count and copy them with perror and EXIT_FAILURE.

argcargvstrtolperrorexit codes
Prerequisites:01. Introduction to C
1

Basic argc/argv

Printing every command-line argument by iterating over argv — argv[0] is the program itself, and quotes keep "two words" together.

argc_argv.c
/*
 * argc_argv.c — Basic argc/argv — command line arguments
 *
 * Key concepts: argc, argv, main parameters
 * Compile: gcc -o prog argc_argv.c
 * Run:     ./prog arg1 arg2
 */
#include <stdio.h>


/*
we need to run this program using the terminal in order to pass it some arguments
but first, lets run it as usual.
*/

int main(int argc, char *argv[]) {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Basic argc/argv\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    printf("  %-6s | %s\n", "Index", "Value");
    printf("  ------ | -----\n");
    for (int i = 0; i < argc; i++) {
        printf("  argv[%d] | \"%s\"%s\n", i, argv[i], i == 0 ? "  (program name)" : "");
    }
    printf("\n");
    if (argc == 1) {
        printf("  TIP: Try running with arguments:\n");
        printf("    ./prog hello world 42\n\n");
    }
    return 0;
}
$ gcc -o argc_argv argc_argv.c
$ ./argc_argv hello world 42 "two words"
Expected Outputclick Run to execute live
══════════════════════════════════════
  Basic argc/argv
══════════════════════════════════════


  Index  | Value
  ------ | -----
  argv[0] | "./argc_argv"  (program name)
  argv[1] | "hello"
  argv[2] | "world"
  argv[3] | "42"
  argv[4] | "two words"
2

Arguments Are Strings

Summing numbers from the command line: atoi("seven") silently gives 0, while strtol shows where it stopped reading so bad input can be refused with EXIT_FAILURE.

args-sum.c
/*
 * args-sum.c — Arguments are strings: turning "42" into the number 42
 *
 * Key concepts: argv[i] is a char*, atoi() vs strtol() with error checking, EXIT_FAILURE
 * Compile: gcc -o sum args-sum.c
 * Run:     ./sum 5 7 30        (then try: ./sum 5 seven 3)
 *
 * "5" + "7" is not 12 — the shell hands every argument to main() as TEXT.
 * atoi("seven") quietly returns 0. strtol() tells you where it stopped reading,
 * so you can refuse input that is not a number.
 */
#include <stdio.h>
#include <stdlib.h>   // atoi, strtol, EXIT_SUCCESS, EXIT_FAILURE

int main(int argc, char *argv[])
{
    if (argc < 2) {
        fprintf(stderr, "Usage: %s number [number ...]\n", argv[0]);
        return EXIT_FAILURE;
    }

    long sum = 0;
    for (int i = 1; i < argc; i++) {
        char *end;
        long value = strtol(argv[i], &end, 10);   // base 10; end = first char NOT used

        printf("argv[%d] = \"%s\"   atoi -> %d   ", i, argv[i], atoi(argv[i]));
        if (end == argv[i] || *end != '\0') {      // nothing read, or junk after the digits
            printf("strtol -> not a number!\n");
            fprintf(stderr, "Error: \"%s\" is not a whole number\n", argv[i]);
            return EXIT_FAILURE;
        }
        printf("strtol -> %ld\n", value);
        sum += value;
    }

    printf("\nSum of %d numbers = %ld\n", argc - 1, sum);
    return EXIT_SUCCESS;
}
$ gcc -o sum args-sum.c
$ ./sum 5 7 30; ./sum 5 seven 3
Expected Outputclick Run to execute live
argv[1] = "5"   atoi -> 5   strtol -> 5
argv[2] = "7"   atoi -> 7   strtol -> 7
argv[3] = "30"   atoi -> 30   strtol -> 30

Sum of 3 numbers = 42
argv[1] = "5"   atoi -> 5   strtol -> 5
argv[2] = "seven"   atoi -> 0   strtol -> not a number!
Error: "seven" is not a whole number
3

Options and a Usage Message

Parsing -n 3 and -u like real Linux commands: options that take the next argument as their value, strcmp, and a usage message with exit status 1 on wrong input.

args-flags.c
/*
 * args-flags.c — Options like real Linux commands: ./greet -n 3 -u Dana
 *
 * Key concepts: walking argv, strcmp(), options that take a value, a usage message, exit codes
 * Compile: gcc -o greet args-flags.c
 * Run:     ./greet -n 3 -u Dana        (then try: ./greet -n)
 *
 * Commands such as `ls -l` or `gcc -o prog file.c` read their options exactly like this:
 * look at each argv[i]; if it is an option, maybe consume the NEXT argument as its value.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>   // strcmp
#include <ctype.h>    // toupper

static void usage(const char *prog)
{
    fprintf(stderr, "Usage: %s [-n times] [-u] name\n", prog);
    fprintf(stderr, "  -n times   say hello this many times (default 1)\n");
    fprintf(stderr, "  -u         shout: print the name in UPPERCASE\n");
}

int main(int argc, char *argv[])
{
    int times = 1;
    int upper = 0;
    const char *name = NULL;

    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-n") == 0) {
            if (i + 1 >= argc) {                  // "-n" must be followed by a value
                fprintf(stderr, "Error: -n needs a number\n");
                usage(argv[0]);
                return EXIT_FAILURE;
            }
            times = atoi(argv[++i]);              // ++i: the value is the NEXT argument
        } else if (strcmp(argv[i], "-u") == 0) {
            upper = 1;
        } else if (argv[i][0] == '-') {
            fprintf(stderr, "Error: unknown option %s\n", argv[i]);
            usage(argv[0]);
            return EXIT_FAILURE;
        } else {
            name = argv[i];                       // anything else is the name
        }
    }

    if (name == NULL) {
        usage(argv[0]);
        return EXIT_FAILURE;
    }

    for (int t = 0; t < times; t++) {
        printf("Hello, ");
        for (const char *c = name; *c; c++)
            putchar(upper ? toupper((unsigned char)*c) : *c);
        printf("!\n");
    }
    return EXIT_SUCCESS;
}
$ gcc -o greet args-flags.c
$ ./greet -n 3 -u Dana; ./greet -n
Expected Outputclick Run to execute live
Hello, DANA!
Hello, DANA!
Hello, DANA!
Error: -n needs a number
Usage: ./greet [-n times] [-u] name
  -n times   say hello this many times (default 1)
  -u         shout: print the name in UPPERCASE
4

File Open with Validation

Opening a file passed via command line, with perror for error messages and EXIT_FAILURE for clean exits. Edit notes.txt in the Files panel and run it again.

argc_argv_another_example.c
/*
 * argc_argv_another_example.c — Opening a file from command line arguments with validation
 *
 * Key concepts: argc/argv, fopen, perror, EXIT_FAILURE
 * Compile: gcc -o prog argc_argv_another_example.c
 * Run:     ./prog arg1 arg2
 */
#include <stdio.h>
#include <stdlib.h>


#include <stdio.h>
#include <stdlib.h>

// lets say we are expecting in our program
// to always get a name of a file
// so we can open it and read from it
// we MUST check for argc/argv size
// if we dont, we might get a segfault


int main(int argc, char *argv[]) {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Opening a file from command line arguments with validation\n");
    printf("══════════════════════════════════════\n\n");
    const int ARGUMENTS_COUNT = 2; 
    if (argc != ARGUMENTS_COUNT) { // if argc is not 2
        perror("Usage: ./a.out <filename>"); // we show the user how to use the program
        return EXIT_FAILURE; // and we return an error
    }
    //here we can continue with the program

    const char* filename = argv[1];

    printf("\n");

    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        perror("  ERROR: Cannot open file");
        return EXIT_FAILURE;
    }

    // Read from the file
    printf("  --- File contents ---\n\n");
    char buffer[100];
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("    %s", buffer);
    }
    printf("\n\n  --- End of file ---\n\n");
    return 0;
}
$ gcc -o argc_file argc_argv_another_example.c
$ ./argc_file notes.txt
Expected Outputclick Run to execute live
══════════════════════════════════════
  Opening a file from command line arguments with validation
══════════════════════════════════════


  --- File contents ---

    Shopping list for the lab:
    - 2 coffees
    - 1 working Makefile
    - patience for segmentation faults


  --- End of file ---
5

A Mini wc

Counting lines, words and characters of every file named on the command line; a missing file is reported with perror and the rest are still counted — the exit status says whether any failed.

args-wc.c
/*
 * args-wc.c — A mini `wc`: count lines, words and characters of every file you name
 *
 * Key concepts: looping over argv, fopen/fgetc/fclose, perror(), keep going after an error
 * Compile: gcc -o mini_wc args-wc.c
 * Run:     ./mini_wc poem.txt notes.txt missing.txt
 *
 * A missing file is reported with perror() but does not stop the others —
 * just like the real `wc`. The exit status tells the shell whether ANY file failed.
 */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>    // isspace

int main(int argc, char *argv[])
{
    if (argc < 2) {
        fprintf(stderr, "Usage: %s file [file ...]\n", argv[0]);
        return EXIT_FAILURE;
    }

    int failed = 0;
    printf("%6s %6s %6s  %s\n", "lines", "words", "chars", "file");

    for (int i = 1; i < argc; i++) {
        FILE *f = fopen(argv[i], "r");
        if (f == NULL) {
            perror(argv[i]);          // e.g. "missing.txt: No such file or directory"
            failed = 1;
            continue;                 // next file
        }

        long lines = 0, words = 0, chars = 0;
        int c, in_word = 0;
        while ((c = fgetc(f)) != EOF) {
            chars++;
            if (c == '\n')
                lines++;
            if (isspace(c))
                in_word = 0;
            else if (!in_word) {      // first letter of a new word
                in_word = 1;
                words++;
            }
        }
        fclose(f);
        printf("%6ld %6ld %6ld  %s\n", lines, words, chars, argv[i]);
    }

    return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
$ gcc -o mini_wc args-wc.c
$ ./mini_wc poem.txt notes.txt missing.txt
Expected Outputclick Run to execute live
 lines  words  chars  file
     4     12     71  poem.txt
     4     17     95  notes.txt
missing.txt: No such file or directory
6

Your Own cp

Copying argv[1] to argv[2] with fopen "r" and "w", fgetc/fputc, and a check on every call — the new copy.txt appears in the Files panel.

args-copy.c
/*
 * args-copy.c — Your own `cp`: copy the file named in argv[1] to the name in argv[2]
 *
 * Key concepts: two files open at once, modes "r" and "w", fgetc/fputc, checking every call
 * Compile: gcc -o mycp args-copy.c
 * Run:     ./mycp notes.txt copy.txt     (then look at copy.txt in the Files panel)
 *
 * Mode "w" creates the destination — or EMPTIES it if it already exists.
 */
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc != 3) {
        fprintf(stderr, "Usage: %s source destination\n", argv[0]);
        return EXIT_FAILURE;
    }

    FILE *src = fopen(argv[1], "r");
    if (src == NULL) {
        perror(argv[1]);
        return EXIT_FAILURE;
    }
    FILE *dst = fopen(argv[2], "w");
    if (dst == NULL) {
        perror(argv[2]);
        fclose(src);                  // do not leak the file we DID open
        return EXIT_FAILURE;
    }

    long bytes = 0;
    int c;
    while ((c = fgetc(src)) != EOF) {
        fputc(c, dst);
        bytes++;
    }

    fclose(src);
    if (fclose(dst) != 0) {           // the data is really written at close: check it too
        perror(argv[2]);
        return EXIT_FAILURE;
    }
    printf("Copied %ld bytes: %s -> %s\n", bytes, argv[1], argv[2]);
    return EXIT_SUCCESS;
}
$ gcc -o mycp args-copy.c
$ ./mycp notes.txt copy.txt
Expected Outputclick Run to execute live
Copied 95 bytes: notes.txt -> copy.txt

Challenges

ChallengeLesson 01.5

Check argc first

The site runs this greeter with no arguments, so argv[1] is NULL and strlen() crashes it. Check argc: if it is not 2, print a usage line containing "Usage" to stderr and return EXIT_FAILURE. Click Edit, change the code, then Run — the site checks how it ended.

args-check.c
/*
 * Challenge (Lesson 01.5): check argc before you touch argv
 *
 * This greeter assumes it got a name. The site runs it with NO arguments,
 * so argv[1] is NULL — and strlen(NULL) crashes the program (SIGSEGV).
 *
 * Your task: if argc is not 2, print a usage line to stderr that contains the
 * word "Usage" (for example: Usage: ./greet name) and return EXIT_FAILURE (1).
 * Done when the program ends with "Exited 1" and the usage line — not a crash.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    // TODO: check argc here

    printf("Hello, %s! Your name has %zu letters.\n", argv[1], strlen(argv[1]));
    return EXIT_SUCCESS;
}
$ gcc -Wall -o greet args-check.c
$ ./greet

Open Full Terminal

Get a Linux terminal with all 6 files from this lesson pre-loaded. Compile, run, and experiment freely.