1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 14:38:11 +00:00

cat: Use Core::Stream::File

This commit is contained in:
Lucas CHOLLET 2022-11-24 12:59:38 +01:00 committed by Tim Flynn
parent 7514e49c17
commit 71c9da90b6

View file

@ -1,16 +1,15 @@
/* /*
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org> * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2022, Lucas Chollet <lucas.chollet@free.fr>
* *
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Vector.h> #include <AK/Vector.h>
#include <LibCore/ArgsParser.h> #include <LibCore/ArgsParser.h>
#include <LibCore/Stream.h>
#include <LibCore/System.h> #include <LibCore/System.h>
#include <LibMain/Main.h> #include <LibMain/Main.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
ErrorOr<int> serenity_main(Main::Arguments arguments) ErrorOr<int> serenity_main(Main::Arguments arguments)
{ {
@ -23,42 +22,27 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
args_parser.add_positional_argument(paths, "File path", "path", Core::ArgsParser::Required::No); args_parser.add_positional_argument(paths, "File path", "path", Core::ArgsParser::Required::No);
args_parser.parse(arguments); args_parser.parse(arguments);
Vector<int> fds; if (paths.is_empty())
if (paths.is_empty()) { paths.append("-"sv);
TRY(fds.try_append(STDIN_FILENO));
} else { Vector<NonnullOwnPtr<Core::Stream::File>> files;
for (auto const& path : paths) { TRY(files.try_ensure_capacity(paths.size()));
int fd;
if (path == "-") { for (auto const& path : paths) {
fd = 0; if (auto result = Core::Stream::File::open_file_or_standard_stream(path, Core::Stream::OpenMode::Read); result.is_error())
} else { warnln("Failed to open {}: {}", path, result.release_error());
auto fd_or_error = Core::System::open(path, O_RDONLY); else
if (fd_or_error.is_error()) { files.unchecked_append(result.release_value());
warnln("Failed to open {}: {}", path, fd_or_error.error());
continue;
}
fd = fd_or_error.release_value();
}
TRY(fds.try_append(fd));
}
} }
TRY(Core::System::pledge("stdio")); TRY(Core::System::pledge("stdio"));
Array<u8, 32768> buffer; Array<u8, 32768> buffer;
for (auto& fd : fds) { for (auto const& file : files) {
for (;;) { while (!file->is_eof()) {
auto buffer_span = buffer.span(); auto const buffer_span = TRY(file->read(buffer));
auto nread = TRY(Core::System::read(fd, buffer_span)); out("{:s}", buffer_span);
if (nread == 0)
break;
buffer_span = buffer_span.trim(nread);
while (!buffer_span.is_empty()) {
auto already_written = TRY(Core::System::write(STDOUT_FILENO, buffer_span));
buffer_span = buffer_span.slice(already_written);
}
} }
TRY(Core::System::close(fd));
} }
return 0; return 0;