From bc23db2c71491f30fbfa221222bb26990ae4c98d Mon Sep 17 00:00:00 2001 From: Tim Morgan Date: Wed, 11 Sep 2019 17:26:48 -0500 Subject: Add stdin support to wc program --- Userland/wc.cpp | 60 ++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 22 deletions(-) (limited to 'Userland/wc.cpp') diff --git a/Userland/wc.cpp b/Userland/wc.cpp index 0910f32abf..499eb85559 100644 --- a/Userland/wc.cpp +++ b/Userland/wc.cpp @@ -16,6 +16,8 @@ struct Count { unsigned long lines = 0; }; +int wc(const String& filename, Vector& counts); + void report(const Count& count) { if (output_lines) { @@ -93,36 +95,50 @@ int main(int argc, char** argv) } Vector files = args.get_single_values(); + Vector counts; + int status; if (files.is_empty()) { - fprintf(stderr, "wc: No files provided\n"); - return 1; + status = wc("", counts); + if (status != 0) + return status; + } else { + for (const auto& f : files) { + status = wc(f, counts); + if (status != 0) + return status; + } } + report(counts); + return 0; +} - Vector counts; - for (const auto& f : files) { - FILE* fp = fopen(f.characters(), "r"); +int wc(const String& filename, Vector& counts) +{ + FILE* fp = nullptr; + if (filename == "" || filename == "-") { + fp = stdin; + } else { + fp = fopen(filename.characters(), "r"); if (fp == nullptr) { - fprintf(stderr, "wc: Could not open file '%s'\n", f.characters()); + fprintf(stderr, "wc: Could not open file '%s'\n", filename.characters()); return 1; } + } - Count count { f }; - char* line = nullptr; - size_t len = 0; - ssize_t n_read = 0; - while ((n_read = getline(&line, &len, fp)) != -1) { - count.lines++; - count.words += count_words(line); - count.chars += n_read; - } - - counts.append(count); - fclose(fp); - if (line) { - free(line); - } + Count count { filename }; + char* line = nullptr; + size_t len = 0; + ssize_t n_read = 0; + while ((n_read = getline(&line, &len, fp)) != -1) { + count.lines++; + count.words += count_words(line); + count.chars += n_read; } - report(counts); + counts.append(count); + fclose(fp); + if (line) { + free(line); + } return 0; } -- cgit v1.2.3