Video Coming Soon...

Created by Zed A. Shaw Updated 2026-04-18 04:15:27

32: head

Implement the first command line tool, head.

View Source file head.cpp Only

// .gnu.org/software/coreutils/manual/html_node/head-invocation.html
#include <fmt/core.h>
#include <iostream>
#include <unistd.h>
#include <fstream>

void collect_head(std::istream& in, int count) {
  std::string line;

  while(in) {
    getline(in, line);
    fmt::println("{}", line);

    if(--count < 0) return;
  }
}


int main(int argc, char* argv[]) {
  int opt = 0;
  int number = 10;

  while((opt = getopt(argc, argv, "n:")) != -1) {
    switch(opt) {
      case 'n':
        number = std::stoi(optarg);
        break;
      default:
        fmt::println("USAGE: head -n <NUM> [file...]");
        return 1;
    }
  }

  if(optind < argc) {
    for(int i = optind; i < argc; i++) {
      std::ifstream in_file{argv[i]};
      collect_head(in_file, number);
    }
  } else {
    collect_head(std::cin, number);
  }
}
Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.