tac: Support concatenating multiple files (#6970)

This commit is contained in:
faxe1008 2021-05-09 15:47:16 +02:00 committed by GitHub
parent 5d14636b95
commit cbb06d7014
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
Notes: sideshowbarker 2024-07-19 17:27:37 +09:00

View file

@ -8,7 +8,6 @@
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
#include <unistd.h>
int main(int argc, char** argv)
{
if (pledge("stdio rpath", nullptr) < 0) {
@ -16,32 +15,41 @@ int main(int argc, char** argv)
return 1;
}
const char* path = nullptr;
Vector<String> paths;
Core::ArgsParser args_parser;
args_parser.set_general_help("Concatenate files or pipes to stdout, last line first.");
args_parser.add_positional_argument(path, "File path", "path", Core::ArgsParser::Required::No);
args_parser.add_positional_argument(paths, "File path(s)", "path", Core::ArgsParser::Required::No);
args_parser.parse(argc, argv);
RefPtr<Core::File> file;
if (path == nullptr) {
file = Core::File::standard_input();
} else {
auto file_or_error = Core::File::open(path, Core::File::ReadOnly);
if (file_or_error.is_error()) {
warnln("Failed to open {}: {}", path, file_or_error.error());
return 1;
auto read_lines = [&](RefPtr<Core::File> file) {
Vector<String> lines;
while (file->can_read_line()) {
lines.append(file->read_line());
}
file = file_or_error.value();
}
file->close();
for (int i = lines.size() - 1; i >= 0; --i)
outln("{}", lines[i]);
};
Vector<String> lines;
while (file->can_read_line()) {
auto line = file->read_line();
lines.append(line);
if (!paths.is_empty()) {
for (auto const& path : paths) {
RefPtr<Core::File> file;
if (path == "-") {
file = Core::File::standard_input();
} else {
auto file_or_error = Core::File::open(path, Core::File::ReadOnly);
if (file_or_error.is_error()) {
warnln("Failed to open {}: {}", path, strerror(errno));
continue;
}
file = file_or_error.release_value();
}
read_lines(file);
}
} else {
read_lines(Core::File::standard_input());
}
for (int i = lines.size() - 1; i >= 0; --i)
outln("{}", lines[i]);
return 0;
}