1
0
Fork 0
mirror of https://github.com/LadybirdBrowser/ladybird.git synced 2025-06-10 18:10:56 +09:00

cat: Use TRY() and LibCore syscall wrappers a lot more :^)

This commit is contained in:
Andreas Kling 2021-11-26 15:54:05 +01:00
parent 58bcb93777
commit 5bf6503ed1
Notes: sideshowbarker 2024-07-18 00:38:54 +09:00

View file

@ -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;