diff options
author | Andreas Kling <kling@serenityos.org> | 2021-11-26 15:54:05 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2021-11-26 23:27:57 +0100 |
commit | 5bf6503ed1d3f4ff905630dbc242118ec00401f8 (patch) | |
tree | 6d61c72debd4a7dd9b276b754b70091d1d8e6e0f | |
parent | 58bcb93777516eaadd1ed5a4d9088681b6577250 (diff) | |
download | serenity-5bf6503ed1d3f4ff905630dbc242118ec00401f8.zip |
cat: Use TRY() and LibCore syscall wrappers a lot more :^)
-rw-r--r-- | Userland/Utilities/cat.cpp | 49 |
1 files 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 <kling@serenityos.org> + * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ @@ -8,13 +8,14 @@ #include <LibCore/ArgsParser.h> #include <LibCore/System.h> #include <LibMain/Main.h> -#include <errno.h> #include <fcntl.h> -#include <stdio.h> -#include <stdlib.h> #include <string.h> #include <unistd.h> +#define IFTRY(binding, expression) \ + if (auto _temporary_result = (expression); !_temporary_result.is_error()) { \ + auto binding = _temporary_result.release_value(); + ErrorOr<int> serenity_main(Main::Arguments arguments) { TRY(Core::System::pledge("stdio rpath", nullptr)); @@ -27,44 +28,38 @@ ErrorOr<int> serenity_main(Main::Arguments arguments) args_parser.parse(arguments); Vector<int> 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; |