logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git

tee.c (2103B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #include <assert.h> /* assert() */
  6. #include <errno.h> /* errno */
  7. #include <signal.h> /* signal() */
  8. #include <stdio.h> /* fprintf(), fgetc(), fputc(), fclose(), fopen() */
  9. #include <stdlib.h> /* calloc(), free(), abort() */
  10. #include <string.h> /* strerror() */
  11. #include <unistd.h> /* getopt(), opt… */
  12. static void
  13. cleanup(FILE **fds)
  14. {
  15. if(fds != NULL)
  16. {
  17. free(fds);
  18. }
  19. }
  20. int
  21. main(int argc, char *argv[])
  22. {
  23. const char *mode = "w";
  24. FILE **fds = {NULL}; // Shut up GCC
  25. int c;
  26. while((c = getopt(argc, argv, ":ai")) != -1)
  27. {
  28. switch(c)
  29. {
  30. case 'a':
  31. mode = "a";
  32. break;
  33. case 'i': /* ignore SIGINT */;
  34. signal(SIGINT, SIG_IGN);
  35. break;
  36. }
  37. }
  38. argc -= optind;
  39. argv += optind;
  40. if(argc > 0)
  41. {
  42. fds = calloc(argc, sizeof(*fds));
  43. if(!fds)
  44. {
  45. fprintf(stderr, "tee: Cannot allocate fd array: %s\n", strerror(errno));
  46. return 1;
  47. }
  48. }
  49. for(int argi = 0; argi < argc; argi++)
  50. {
  51. assert(argv[argi]);
  52. // POSIX: implementations shouldn't treat '-' as stdin
  53. fds[argi] = fopen(argv[argi], mode);
  54. if(fds[argi] == NULL)
  55. {
  56. fprintf(stderr, "tee: Error opening ‘%s’: %s\n", argv[argi], strerror(errno));
  57. cleanup(fds);
  58. return 1;
  59. }
  60. }
  61. // main loop, note that failed writes shouldn't make tee exit
  62. int err = 0;
  63. while((c = fgetc(stdin)) != EOF)
  64. {
  65. if(fputc(c, stdout) == EOF)
  66. {
  67. fprintf(stderr, "tee: Error writing ‘<stdout>’: %s\n", strerror(errno));
  68. err = 1;
  69. errno = 0;
  70. }
  71. for(int argi = 0; argi < argc; argi++)
  72. {
  73. if(fputc(c, fds[argi]) == EOF)
  74. {
  75. fprintf(stderr, "tee: Error writing to argument %d: %s\n", argi, strerror(errno));
  76. err = 1;
  77. errno = 0;
  78. }
  79. }
  80. }
  81. // cleanup
  82. for(int argi = 0; argi < argc; argi++)
  83. {
  84. if(fclose(fds[argi]) != 0)
  85. {
  86. fprintf(stderr, "tee: I/O error when closing file '%s': %s\n", argv[argi], strerror(errno));
  87. err++;
  88. }
  89. }
  90. cleanup(fds);
  91. return err;
  92. }