From 9161a33154380814f7bffe441e7a237f07039160 Mon Sep 17 00:00:00 2001 From: Henk Kalkwater Date: Sat, 5 Dec 2020 13:03:47 +0100 Subject: [PATCH] Allow reading input from other files than stdin --- README.txt | 4 ++-- source/app.d | 19 +++++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/README.txt b/README.txt index dbb3241..63949b5 100644 --- a/README.txt +++ b/README.txt @@ -6,6 +6,6 @@ Run "dub". HOW TO RUN: -./oac-2020 [day] [part] +./oac-2020 [DAY] [PART] -The program reads it input from stdin. +The program reads it input from stdin if INPUT_FILE is not specified or if INPUT_FILE is equal to "-". diff --git a/source/app.d b/source/app.d index ae075ac..4babd2a 100644 --- a/source/app.d +++ b/source/app.d @@ -1,6 +1,7 @@ import core.stdc.stdlib; import std.conv; +import std.exception; import std.format; import std.stdio; import std.getopt; @@ -28,7 +29,10 @@ void printUsage(string name) { } void printUsage(string name, string message) { - stderr.writeln("USAGE: %s [day] [part]".format(name)); + stderr.writeln("USAGE: %s [DAY] [PART] ".format(name)); + stderr.writeln(" DAY = int between 1 and 25 (inclusive), specifiying the day to run"); + stderr.writeln(" PART = int between 1 and 2 (inclusive), specifiying the part to run"); + stderr.writeln(" INPUT_FILE = file to read from. '-' or missing implies stdin"); if (message != null) { stderr.writeln(message); } @@ -56,9 +60,20 @@ void main(string[] args) { } catch (ConvException e) { printUsage(args[0], "[part] is not an integer"); } + + File file; + if (args.length < 4 || args[3] == "-") { + file = stdin; + } else { + try { + file = File(args[3], "rb"); + } catch (ErrnoException e) { + printUsage(args[0], "Error %d while opening input file: %s".format(e.errno, e.message)); + } + } try { - Variant result = programs[day - 1](part, stdin, args[3..$]); + Variant result = programs[day - 1](part, file, args[3..$]); writeln(result); } catch(ArgumentException e) { printUsage(args[0], e.msg);