From 5bf6503ed1d3f4ff905630dbc242118ec00401f8 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Fri, 26 Nov 2021 15:54:05 +0100 Subject: [PATCH] cat: Use TRY() and LibCore syscall wrappers a lot more :^) --- Userland/Utilities/cat.cpp | 49 +++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 27 deletions(-) diff --git a/Userland/Utilities/cat.cpp b/Userland/Utilities/cat.cpp index 78b1043725..c749cbeff5 100644 --- a/Userland/Utilities/cat.cpp +++ b/Userland/Utilities/cat.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2020, Andreas Kling + * Copyright (c) 2018-2021, Andreas Kling * * SPDX-License-Identifier: BSD-2-Clause */ @@ -8,13 +8,14 @@ #include #include #include -#include #include -#include -#include #include #include +#define IFTRY(binding, expression) \ + if (auto _temporary_result = (expression); !_temporary_result.is_error()) { \ + auto binding = _temporary_result.release_value(); + ErrorOr serenity_main(Main::Arguments arguments) { TRY(Core::System::pledge("stdio rpath", nullptr)); @@ -27,44 +28,38 @@ ErrorOr serenity_main(Main::Arguments arguments) args_parser.parse(arguments); Vector fds; - if (!paths.is_empty()) { + if (paths.is_empty()) { + TRY(fds.try_append(STDIN_FILENO)); + } else { for (auto const& path : paths) { int fd; if (path == "-") { fd = 0; - } else if ((fd = open(path.characters(), O_RDONLY)) == -1) { - warnln("Failed to open {}: {}", path, strerror(errno)); - continue; + } else { + auto fd_or_error = Core::System::open(path, O_RDONLY); + if (fd_or_error.is_error()) { + warnln("Failed to open {}: {}", path, fd_or_error.error()); + continue; + } + fd = fd_or_error.release_value(); } - fds.append(fd); + TRY(fds.try_append(fd)); } - } else { - fds.append(0); } TRY(Core::System::pledge("stdio", nullptr)); for (auto& fd : fds) { for (;;) { - char buf[32768]; - ssize_t nread = read(fd, buf, sizeof(buf)); + char buffer[32768]; + auto nread = TRY(Core::System::read(fd, buffer, sizeof(buffer))); if (nread == 0) break; - if (nread < 0) { - perror("read"); - return 2; - } - size_t already_written = 0; - while (already_written < (size_t)nread) { - ssize_t nwritten = write(1, buf + already_written, nread - already_written); - if (nwritten < 0) { - perror("write"); - return 3; - } - already_written += nwritten; - } + ssize_t already_written = 0; + while (already_written < nread) + already_written += TRY(Core::System::write(STDOUT_FILENO, buffer + already_written, nread - already_written)); } - close(fd); + TRY(Core::System::close(fd)); } return 0;