tail.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. /*
  3. * Copyright (C) 2022, 2023 Ferass El Hafidi <vitali64pmemail@protonmail.com>
  4. */
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <stdio.h>
  8. #include <errno.h>
  9. #include <string.h>
  10. #include <stdlib.h>
  11. #define REQ_PRINT_USAGE /* Require print_usage() from ../common/common.h */
  12. #define REQ_ERRPRINT /* Require errprint() from ../common/common.h */
  13. #define DESCRIPTION "Copy the last part of files."
  14. #define OPERANDS "[-n number] [file] ..."
  15. #include "../common/common.h"
  16. int main(int argc, char *const argv[]) {
  17. int argument, i = 1, lines, file_lines;
  18. FILE *file;
  19. char s[4096], *argv0 = strdup(argv[0]);
  20. while ((argument = getopt(argc, argv, "n:")) != -1) {
  21. if (argument == '?' || argument == ':') {
  22. print_usage(argv[0], DESCRIPTION, OPERANDS, VERSION);
  23. return 1;
  24. }
  25. else if (argument == 'n') {
  26. lines = strtol(optarg, NULL, 10);
  27. if (errno) return errprint(argv[0], "strtol()", errno);
  28. }
  29. else
  30. lines = 10;
  31. } argc -= optind; argv += optind;
  32. if (argc < 1) {
  33. while (read(STDIN_FILENO, s, 4096) > 0)
  34. printf("%s", s);
  35. }
  36. if (!lines) lines = 10;
  37. for (i = 0; i != argc; i++) {
  38. if (strcmp(argv[i], "-")) file = fopen(argv[i], "r");
  39. else while (read(STDIN_FILENO, s, 4096) > 0) printf("%s", s);
  40. if (file == NULL)
  41. return errprint(argv[0], argv[i], errno); /* Something went wrong */
  42. while (fgets(s, 4096, file) != NULL)
  43. file_lines++; /* Get number of lines */
  44. fclose(file);
  45. file_lines = file_lines - lines;
  46. if (strcmp(argv[i], "-")) file = fopen(argv[i], "r");
  47. while (fgets(s, 4096, file) != NULL) {
  48. if (errno) return errprint(argv0, argv[i], errno);
  49. if (file_lines == 0) printf("%s", s);
  50. else file_lines--;
  51. }
  52. }
  53. return errprint(argv0, NULL, errno);
  54. }