logo

utils

~/.local/bin tools and git-hooks git clone https://hacktivis.me/git/utils.git

echo.c (1107B)


  1. // Collection of Unix tools, comparable to coreutils
  2. // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
  4. #define _POSIX_C_SOURCE 200809L
  5. #include <stdio.h> /* perror */
  6. #include <stdlib.h> /* malloc */
  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. char *buffer, *buffer_p;
  14. int err = 0;
  15. if(argc < 2)
  16. {
  17. arg_len++;
  18. }
  19. for(int i = 1; i < argc; i++)
  20. {
  21. arg_len += strlen(argv[i]) + 1; // str + space|newline
  22. }
  23. buffer = malloc(arg_len);
  24. if(buffer == NULL)
  25. {
  26. perror("malloc(arg_len)");
  27. return 1;
  28. }
  29. buffer_p = buffer;
  30. for(int i = 1; i < argc; i++)
  31. {
  32. /* flawfinder: ignore, consider that arguments are safely separated by NULL */
  33. buffer_p = strcpy(buffer_p, argv[i]);
  34. buffer_p += strlen(buffer_p);
  35. if(i < argc - 1)
  36. {
  37. *buffer_p++ = ' ';
  38. }
  39. }
  40. *buffer_p++ = '\n';
  41. if(write(1, buffer, arg_len) < (ssize_t)arg_len)
  42. {
  43. perror("write(1, buffer, arg_len)");
  44. err++;
  45. }
  46. free(buffer);
  47. return err;
  48. }