Video Coming Soon...

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

33: tail

Implement the first command line tool, tail.

View Source file tail.cpp Only

//https://www.gnu.org/software/coreutils/manual/html_node/tail-invocation.html 
#include <fmt/core.h>
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <vector>
#include <algorithm>

void collect_tail(std::istream& in, int count) {
  std::string line;
  std::vector<std::string> lines;

  while(in) {
    getline(in, line);
    lines.emplace_back(line);
  }

  int start = std::max(0, int(lines.size()) - count);

  for(size_t i = start; i < lines.size(); i++) {
    fmt::println("{}", lines[i]);
  }
}


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: tail -n <NUM> [file...]");
        return 1;
    }
  }

  if(optind < argc) {
    for(int i = optind; i < argc; i++) {
      std::ifstream in_file{argv[i]};
      collect_tail(in_file, number);
    }
  } else {
    collect_tail(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.