1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 11:07:45 +00:00

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

View file

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