logo

utils-std

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

echo.c (1015B)


  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 <stdbool.h>
  6. #include <stdio.h> // perror
  7. #include <string.h> // strlen
  8. #include <unistd.h> // write
  9. int
  10. main(int argc, char *argv[])
  11. {
  12. size_t arg_len = 0;
  13. bool opt_n = false;
  14. argc--;
  15. argv++;
  16. if(argc > 0 && strncmp(*argv, "-n", 3) == 0)
  17. {
  18. opt_n = true;
  19. argc--;
  20. argv++;
  21. }
  22. for(int i = 0; i < argc; i++)
  23. {
  24. size_t len = strlen(argv[i]);
  25. argv[i][len] = ' ';
  26. arg_len += len + 1; // str + space
  27. }
  28. if(arg_len == 0)
  29. {
  30. if(opt_n) return 0;
  31. if(write(1, "\n", 1) < 1)
  32. {
  33. perror("echo: error: Failed writing");
  34. return 1;
  35. }
  36. return 0;
  37. }
  38. else
  39. argv[0][arg_len - 1] = '\n';
  40. if(opt_n) arg_len--; // no newline
  41. ssize_t nwrite = write(1, *argv, arg_len);
  42. if(nwrite < (ssize_t)arg_len)
  43. {
  44. perror("echo: error: Failed writing");
  45. return 1;
  46. }
  47. return 0;
  48. }