more command line arguments

This commit is contained in:
Eric Mertens 2023-01-31 10:17:01 -08:00
parent df195e65b5
commit c074e66157

View File

@ -6,18 +6,62 @@
#include <memory>
#include <fstream>
#include <utility>
#include <unistd.h>
#define DOCTEST_CONFIG_IMPLEMENT
#include <doctest.h>
auto main(int argc, char ** argv) -> int
{
if (std::getenv("DOCTEST")) {
return doctest::Context{argc, argv}.run();
}
bool run_tests {};
char const* in_name {};
char const* out_name {};
try {
Main(std::cin, std::cout);
int ch;
while ((ch = getopt(argc, argv, ":hi:o:t")) != -1) {
switch (ch) {
case 'i': in_name = optarg; break;
case 'o': out_name = optarg; break;
case 't': run_tests = true; break;
case ':':
std::cerr << "Missing argument to -" << char(optopt) << std::endl;
return 1;
case 'h':
std::cerr << "Usage: " << argv[0] << " [-i INPUT] [-o OUTPUT] [-t]" << std::endl;
return 0;
case '?':
default:
std::cerr << "Unknown flag -" << char(optopt) << std::endl;
return 1;
}
}
if (run_tests) {
return doctest::Context{argc, argv}.run();
}
std::unique_ptr<std::istream, void(*)(std::istream*)> in
{in_name
? decltype(in){new std::ifstream{in_name}, [](auto p) { delete p; }}
: decltype(in){&std::cin, [](auto){}}};
if (in->fail()) {
std::cerr << "Bad input file" << std::endl;
return 1;
}
std::unique_ptr<std::ostream, void(*)(std::ostream*)> out
{out_name
? decltype(out){new std::ofstream{out_name}, [](auto p) { delete p; }}
: decltype(out){&std::cout, [](auto){}}};
if (out->fail()) {
std::cerr << "Bad output file" << std::endl;
return 1;
}
Main(*in, *out);
} catch (std::exception const& e) {
std::cerr << "Program failed: " << e.what() << std::endl;
return 1;