From b556bfe8eb4df813e0758b3d39c0ac77dc1ac86e Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Tue, 27 Sep 2022 20:46:03 +0200 Subject: [PATCH] rev: Read from stdin if the filename '-' is given The implementation of `rev` found on Linux systems does not have this behavior, however other utilities do offer this behavior and so there really isn't too much of an argument to be made for *not* having this as a feature. --- Userland/Utilities/rev.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/Userland/Utilities/rev.cpp b/Userland/Utilities/rev.cpp index a653177e87..258c2926b0 100644 --- a/Userland/Utilities/rev.cpp +++ b/Userland/Utilities/rev.cpp @@ -28,12 +28,16 @@ ErrorOr serenity_main(Main::Arguments arguments) if (!paths.is_empty()) { for (auto const& path : paths) { - FILE* stream = fopen(String(path).characters(), "r"); - if (!stream) { - warnln("Failed to open {}: {}", path, strerror(errno)); - continue; + if (path == "-") { + streams.append(stdin); + } else { + FILE* stream = fopen(String(path).characters(), "r"); + if (!stream) { + warnln("Failed to open {}: {}", path, strerror(errno)); + continue; + } + streams.append(stream); } - streams.append(stream); } } else { streams.append(stdin); @@ -43,8 +47,12 @@ ErrorOr serenity_main(Main::Arguments arguments) ScopeGuard guard = [&] { free(buffer); for (auto* stream : streams) { - if (fclose(stream)) + // If the user passes '-' as an argument multiple times, then we will end up trying to + // close stdin multiple times. This will cause `fclose()` to fail but with no error, so + // we need to manually check errno. + if (fclose(stream) && errno != 0) { perror("fclose"); + } } };