logo

utils

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

lolcat.c (1876B)


  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 <errno.h> /* errno */
  6. #include <math.h> /* sin() */
  7. #include <stdio.h> /* fgetc(), fputc(), printf(), fopen(), fclose() */
  8. #include <string.h> /* strerror() */
  9. void
  10. rainbow(double freq, int i)
  11. {
  12. double red, green, blue;
  13. double pi = 3.14159;
  14. red = sin(freq * i + 0) * 127 + 128;
  15. green = sin(freq * i + 2 * pi / 3) * 127 + 128;
  16. blue = sin(freq * i + 4 * pi / 3) * 127 + 128;
  17. printf("[38;2;%02d;%02d;%02dm", (int)red, (int)green, (int)blue);
  18. }
  19. int
  20. concat(FILE *stream)
  21. {
  22. double freq = 0.1;
  23. int i = 0;
  24. int c;
  25. errno = 0;
  26. while((c = fgetc(stream)) != EOF)
  27. {
  28. rainbow(freq, i);
  29. i++;
  30. if(c == '')
  31. {
  32. printf("^[");
  33. continue;
  34. }
  35. if(fputc(c, stdout) == EOF)
  36. {
  37. fprintf(stderr, "\nWrite error: %s\n", strerror(errno));
  38. return 1;
  39. }
  40. }
  41. if(c == EOF && errno != 0)
  42. {
  43. fprintf(stderr, "\nRead error: %s\n", strerror(errno));
  44. return 1;
  45. }
  46. return 0;
  47. }
  48. int
  49. main(int argc, char *argv[])
  50. {
  51. int ret = 0;
  52. if(argc <= 1)
  53. {
  54. ret = concat(stdin);
  55. goto end;
  56. }
  57. for(int argi = 1; argi < argc; argi++)
  58. {
  59. if(strncmp(argv[argi], "-", 2) == 0)
  60. {
  61. ret = concat(stdin);
  62. if(ret != 0)
  63. {
  64. goto end;
  65. }
  66. }
  67. else if(strncmp(argv[argi], "--", 3) == 0)
  68. {
  69. continue;
  70. }
  71. else
  72. {
  73. FILE *file = fopen(argv[argi], "r");
  74. if(!file)
  75. {
  76. fprintf(stderr, "\nError opening ā€˜%sā€™: %s\n", argv[argi], strerror(errno));
  77. ret = 1;
  78. goto end;
  79. }
  80. else
  81. {
  82. ret = concat(file);
  83. if(ret != 0)
  84. {
  85. goto end;
  86. }
  87. ret = fclose(file);
  88. if(ret != 0)
  89. {
  90. goto end;
  91. }
  92. }
  93. }
  94. }
  95. end:
  96. printf("");
  97. return ret;
  98. }