Skip to content

Commit

Permalink
tac: Support concatenating multiple files (SerenityOS#6970)
Browse files Browse the repository at this point in the history
  • Loading branch information
faxe1008 committed May 9, 2021
1 parent 5d14636 commit cbb06d7
Showing 1 changed file with 28 additions and 20 deletions.
48 changes: 28 additions & 20 deletions Userland/Utilities/tac.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,40 +8,48 @@
#include <LibCore/ArgsParser.h>
#include <LibCore/File.h>
#include <unistd.h>

int main(int argc, char** argv)
{
if (pledge("stdio rpath", nullptr) < 0) {
perror("pledge");
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;
}

0 comments on commit cbb06d7

Please sign in to comment.