Video Coming Soon...
32: head
The head tool will print out the first -n number of lines of a file. By default it prints 10 lines, but you'll implement the -n option to allow for more or less.
The Challenge
As usual, read the instructions for head to understand what you're making. Get the -n option working and then pick two more options to implement. You should also try to do this on your own before peeking at my initial solution.
Also remember that if you have to peek often that's alright. It's how you learn and eventually can make these on your own.
The Code
See my first version of head
View Source file head.cpp Only#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);
}
}
The Discussion
The head tool is fairly simple since you can loop and count until you've reached the end. The next projects is tail which is more involved since you have to print the end of a file, but the premise is the same for both.
Further Study
You should be seeing that many of these tools follow similar pattern:
- Get command line arguments.
- Set variables based on the arguments.
- Open files or stdin.
- Do stuff with the files based on the variables.
You could update your starter project to have these base things ready to go for future projects.
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.