Skip to main content

Lesson 5 of 5

Mini Project Part 11 - getopt-Powered CLI Tool

Build a POSIX `cat`-style file utility that: reads files using POSIX `open`/`read`/`close`, parses options with `getopt_long` (`-n` number lines, `-e` show line endings, `--help`, `--version`), writes to stdout via `write`, and prints statistics with `-s`. Fully const-correct, with robust `errno` error handling.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

pcat - POSIX cat Clone with getopt_long

pcat - POSIX cat Clone with getopt_long
/* pcat.c - POSIX cat clone with getopt_long
   Usage: pcat [-n] [-e] [-s] [--help] [--version] [FILE...] */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <errno.h>

#define VERSION "1.0.0"
#define BUF_SZ  4096

typedef struct {
    int verbose;
    int number_lines;
    int show_ends;    /* show $ at end of each line */
    int stats;
} Opts;

static void usage(const char *prog) {
    printf("Usage: %s [OPTIONS] [FILE...]
"
           "  -n, --number      Number output lines
"
           "  -e, --show-ends   Show $ at end of lines
"
           "  -s, --stats       Show byte/line stats
"
           "  -h, --help        Show help
"
           "      --version     Show version
", prog);
}

static int process_fd(int fd, const Opts *opts,
                      long *total_bytes, long *total_lines) {
    char   buf[BUF_SZ];
    long   lno   = 1;
    int    bol   = 1;   /* beginning of line */
    ssize_t nr;

    while ((nr = read(fd, buf, sizeof(buf))) > 0) {
        *total_bytes += nr;
        for (ssize_t i = 0; i < nr; i++) {
            char c = buf[i];
            if (opts->number_lines && bol) {
                dprintf(STDOUT_FILENO, "%6ld	", lno++);
                bol = 0;
            }
            if (c == '
') {
                if (opts->show_ends) write(STDOUT_FILENO, "$", 1);
                write(STDOUT_FILENO, "
", 1);
                bol = 1;
                (*total_lines)++;
            } else {
                write(STDOUT_FILENO, &c, 1);
            }
        }
    }
    return nr < 0 ? -1 : 0;
}

int main(int argc, char **argv) {
    Opts opts = {0};

    static struct option long_opts[] = {
        {"number",    no_argument, NULL, 'n'},
        {"show-ends", no_argument, NULL, 'e'},
        {"stats",     no_argument, NULL, 's'},
        {"help",      no_argument, NULL, 'h'},
        {"version",   no_argument, NULL, 'V'},
        {NULL, 0, NULL, 0}
    };

    int opt;
    while ((opt = getopt_long(argc, argv, "nesh", long_opts, NULL)) != -1) {
        switch (opt) {
            case 'n': opts.number_lines = 1; break;
            case 'e': opts.show_ends    = 1; break;
            case 's': opts.stats        = 1; break;
            case 'h': usage(argv[0]); return 0;
            case 'V': printf("pcat version %s
", VERSION); return 0;
            default:  usage(argv[0]); return 1;
        }
    }

    long total_bytes = 0, total_lines = 0;
    int  exit_code   = 0;

    if (optind >= argc) {
        /* No files - read stdin */
        if (process_fd(STDIN_FILENO, &opts, &total_bytes, &total_lines) != 0) {
            perror("stdin"); exit_code = 1;
        }
    } else {
        for (int i = optind; i < argc; i++) {
            int fd = open(argv[i], O_RDONLY);
            if (fd < 0) {
                fprintf(stderr, "pcat: %s: %s
", argv[i], strerror(errno));
                exit_code = 1;
                continue;
            }
            if (process_fd(fd, &opts, &total_bytes, &total_lines) != 0) {
                fprintf(stderr, "pcat: read error on %s: %s
", argv[i], strerror(errno));
                exit_code = 1;
            }
            close(fd);
        }
    }

    if (opts.stats) {
        fprintf(stderr, "
[stats] bytes=%ld  lines=%ld
", total_bytes, total_lines);
    }

    return exit_code;
}
/* Build: gcc -Wall -Wextra -std=c99 pcat.c -o pcat
   Test:  ./pcat -n  /etc/hostname
          ./pcat -ne /etc/hostname
          ./pcat -s  /etc/hostname /etc/os-release
          echo "hello world" | ./pcat -n         */

Common Mistakes

  • Printing byte-by-byte with printf/putchar for large files - this approach makes a write syscall for every byte. Real cat implementations use a buffer and write the whole line or buffer at once for performance.
  • Not handling the stdin case (no file arguments) - professional tools read from stdin when no files are given, enabling use in pipelines: `echo hello | pcat -n`.
  • `dprintf` is not on all platforms - `dprintf(STDOUT_FILENO, ...)` is POSIX but not standard C. For maximum portability, use `printf` for formatted output and `write` for raw bytes, not mixed.

Tip

Tip

Practice Mini Project Part 11 getoptPowered CLI Tool in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Professional CLI tools follow the UNIX philosophy: parse flags, process streams, emit clean output

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Part 11 getoptPowered CLI Tool from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Part 11 getoptPowered CLI Tool is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • Build a POSIX `cat`-style file utility that: reads files using POSIX `open`/`read`/`close`, parses options with `getopt_long` (`-n` number lines, `-e` show line endings, `--help`, `--version`), writes to stdout via `write`, and prints statistics with `-s`.
  • Printing byte-by-byte with printf/putchar for large files - this approach makes a write syscall for every byte. Real cat implementations use a buffer and write the whole line or buffer at once for performance.
  • Not handling the stdin case (no file arguments) - professional tools read from stdin when no files are given, enabling use in pipelines: `echo hello | pcat -n`.
  • `dprintf` is not on all platforms - `dprintf(STDOUT_FILENO, ...)` is POSIX but not standard C. For maximum portability, use `printf` for formatted output and `write` for raw bytes, not mixed.

Topics in This Module

0/5 done