Video Coming Soon...
29: cat
Implement the first command line tool, cat.
// https://www.gnu.org/software/coreutils/manual/html_node/cat-invocation.html
#include <iostream>
#include <fstream>
#include <string>
#include <fmt/core.h>
#include <unistd.h>
void dump_file(std::istream& in, bool number, bool squeeze) {
std::string line;
int line_count = 0;
while(in) {
getline(in, line);
line_count++;
if(line == "" && squeeze) continue;
if(number) {
fmt::println("{}: {}", line_count, line);
} else {
fmt::println("{}", line);
}
}
}
int main(int argc, char* argv[]) {
int opt = 0;
bool number = false;
bool squeeze = false;
while((opt = getopt(argc, argv, "ns")) != -1) {
switch(opt) {
case 'n':
number = true;
break;
case 's':
squeeze = true;
break;
default:
fmt::print("USAGE: cat -ns [file]");
return 1;
}
}
if(optind < argc) {
// there's files to process
for(int i = optind; i < argc; i++) {
std::ifstream in_file{argv[i]};
dump_file(in_file, number, squeeze);
}
} else {
dump_file(std::cin, number, squeeze);
}
}
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.