logo

utils-std

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

yes.c (948B)


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