logo

utils

Old programs, got split in utils-std and utils-extra git clone https://hacktivis.me/git/utils.git

pat.c (1735B)


  1. // Collection of Unix tools, comparable to coreutils
  2. // SPDX-FileCopyrightText: 2017-2023 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #include <errno.h> /* errno */
  6. #include <fcntl.h> /* open(), O_RDONLY */
  7. #include <stdio.h> /* fprintf(), fwrite(), BUFSIZ */
  8. #include <string.h> /* strerror(), strncmp() */
  9. #include <unistd.h> /* read(), close() */
  10. int files = 1;
  11. int
  12. concat(int fd, const char *fdname)
  13. {
  14. ssize_t c;
  15. char buf[BUFSIZ];
  16. // File Number as an esccape/containment solution
  17. printf("\n### File %d << %s >> ###\n", files++, fdname);
  18. while((c = read(fd, buf, sizeof(buf))) > 0)
  19. {
  20. if(fwrite(buf, (size_t)c, 1, stdout) < 0)
  21. {
  22. fprintf(stderr, "pat: Error writing: %s\n", strerror(errno));
  23. return 1;
  24. }
  25. }
  26. if(c < 0)
  27. {
  28. fprintf(stderr, "pat: Error reading ‘%s’: %s\n", fdname, strerror(errno));
  29. return 1;
  30. }
  31. return 0;
  32. }
  33. int
  34. main(int argc, char *argv[])
  35. {
  36. if(argc <= 1)
  37. {
  38. printf("### 1 Files ###");
  39. return concat(0, "<stdin>");
  40. }
  41. // no \n, concat starts with one
  42. printf("### %d Files ###", argc - 1);
  43. for(int argi = 1; argi < argc; argi++)
  44. {
  45. if(strncmp(argv[argi], "-", 2) == 0)
  46. {
  47. if(concat(0, "<stdin>") != 0)
  48. {
  49. return 1;
  50. }
  51. }
  52. else if(strncmp(argv[argi], "--", 3) == 0)
  53. {
  54. continue;
  55. }
  56. else
  57. {
  58. int fd = open(argv[argi], O_RDONLY);
  59. if(fd < 0)
  60. {
  61. fprintf(stderr, "pat: Error opening ‘%s’: %s\n", argv[argi], strerror(errno));
  62. return 1;
  63. }
  64. if(concat(fd, argv[argi]) != 0)
  65. {
  66. return 1;
  67. }
  68. if(close(fd) < 0)
  69. {
  70. fprintf(stderr, "pat: Error closing ‘%s’: %s\n", argv[argi], strerror(errno));
  71. return 1;
  72. }
  73. }
  74. }
  75. return 0;
  76. }