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

tac: Unbreak reading from standard input

Since Core::File does not handle streaming input properly (see #5093
and #4198), we use the LibC APIs instead.
This commit is contained in:
SeekingBlues 2021-10-13 19:59:18 -04:00 committed by Brian Gianforcaro
parent c63bdba955
commit 6d4e58efea

View file

@ -4,10 +4,11 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <AK/Vector.h>
#include <LibCore/ArgsParser.h> #include <LibCore/ArgsParser.h>
#include <LibCore/File.h> #include <errno.h>
#include <string.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) {
@ -22,33 +23,59 @@ int main(int argc, char** argv)
args_parser.add_positional_argument(paths, "File path(s)", "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);
auto read_lines = [&](RefPtr<Core::File> file) { Vector<FILE*> streams;
Vector<String> lines; auto num_paths = paths.size();
while (file->can_read_line()) { streams.ensure_capacity(num_paths ? num_paths : 1);
lines.append(file->read_line());
}
file->close();
for (int i = lines.size() - 1; i >= 0; --i)
outln("{}", lines[i]);
};
if (!paths.is_empty()) { if (!paths.is_empty()) {
for (auto const& path : paths) { for (auto const& path : paths) {
RefPtr<Core::File> file; FILE* stream = nullptr;
if (path == "-") { if (path == "-"sv) {
file = Core::File::standard_input(); stream = stdin;
} else { } else {
auto file_or_error = Core::File::open(path, Core::OpenMode::ReadOnly); stream = fopen(path.characters(), "r");
if (file_or_error.is_error()) { if (!stream) {
warnln("Failed to open {}: {}", path, strerror(errno)); warnln("Failed to open {}: {}", path, strerror(errno));
continue; continue;
} }
file = file_or_error.release_value();
} }
read_lines(file); streams.append(stream);
} }
} else { } else {
read_lines(Core::File::standard_input()); streams.append(stdin);
}
char* buffer = nullptr;
ScopeGuard guard = [&] {
free(buffer);
for (auto* stream : streams) {
if (fclose(stream))
perror("fclose");
}
};
if (pledge("stdio", nullptr) < 0) {
perror("pledge");
return 1;
}
for (auto* stream : streams) {
Vector<String> lines;
for (;;) {
size_t n = 0;
errno = 0;
ssize_t buflen = getline(&buffer, &n, stream);
if (buflen == -1) {
if (errno != 0) {
perror("getline");
return 1;
}
break;
}
lines.append({ buffer, Chomp });
}
for (int i = lines.size() - 1; i >= 0; --i)
outln("{}", lines[i]);
} }
return 0; return 0;