Skip to content

Instantly share code, notes, and snippets.

@kevinkreiser
Created May 11, 2016 12:45
Show Gist options
  • Save kevinkreiser/d0fdfeebd42ba5d9a8e138c1f4fd55fe to your computer and use it in GitHub Desktop.
Save kevinkreiser/d0fdfeebd42ba5d9a8e138c1f4fd55fe to your computer and use it in GitHub Desktop.
naive implementation of cat (without pipes)
#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>
int main(int argc, char** argv) {
if(argc < 2) {
std::cerr << "cat: Pass me a file\n";
return 2;
}
std::string file_name(argv[1]);
std::ifstream file_handle;
file_handle.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
file_handle.open(file_name.c_str());
std::string file_contents((std::istreambuf_iterator<char>(file_handle)),
std::istreambuf_iterator<char>());
std::cout << file_contents;
}
catch(const std::exception& e) {
std::cerr << "cat: " << file_name << ": " << e.what() << std::endl;
return 2;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment