rev.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (c) 2021, Thomas Voss <mail@thomasvoss.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/ArgsParser.h>
  7. #include <LibCore/System.h>
  8. #include <LibMain/Main.h>
  9. #include <errno.h>
  10. #include <string.h>
  11. #include <unistd.h>
  12. ErrorOr<int> serenity_main(Main::Arguments arguments)
  13. {
  14. TRY(Core::System::pledge("stdio rpath"sv));
  15. Vector<StringView> paths;
  16. Core::ArgsParser args_parser;
  17. args_parser.set_general_help("Concatente files to stdout with each line in reverse.");
  18. args_parser.add_positional_argument(paths, "File path", "path", Core::ArgsParser::Required::No);
  19. args_parser.parse(arguments);
  20. Vector<FILE*> streams;
  21. auto num_paths = paths.size();
  22. streams.ensure_capacity(num_paths ? num_paths : 1);
  23. if (!paths.is_empty()) {
  24. for (auto const& path : paths) {
  25. FILE* stream = fopen(String(path).characters(), "r");
  26. if (!stream) {
  27. warnln("Failed to open {}: {}", path, strerror(errno));
  28. continue;
  29. }
  30. streams.append(stream);
  31. }
  32. } else {
  33. streams.append(stdin);
  34. }
  35. char* buffer = nullptr;
  36. ScopeGuard guard = [&] {
  37. free(buffer);
  38. for (auto* stream : streams) {
  39. if (fclose(stream))
  40. perror("fclose");
  41. }
  42. };
  43. TRY(Core::System::pledge("stdio"sv));
  44. for (auto* stream : streams) {
  45. for (;;) {
  46. size_t n = 0;
  47. errno = 0;
  48. ssize_t buflen = getline(&buffer, &n, stream);
  49. if (buflen == -1) {
  50. if (errno != 0) {
  51. perror("getline");
  52. return 1;
  53. }
  54. break;
  55. }
  56. outln("{}", String { buffer, Chomp }.reverse());
  57. }
  58. }
  59. return 0;
  60. }