Cat with colors
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rccat.c 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5. #include <unistd.h>
  6. #define KNRM "\x1B[0m"
  7. #define KRED "\x1B[31m"
  8. #define KGRN "\x1B[32m"
  9. #define KYEL "\x1B[33m"
  10. #define KBLU "\x1B[34m"
  11. #define KMAG "\x1B[35m"
  12. #define KCYN "\x1B[36m"
  13. #define KWHT "\x1B[37m"
  14. const char *colors[7] = {KNRM, KRED, KGRN, KYEL, KBLU, KMAG, KCYN};
  15. int lastcolor = 0;
  16. void printColors(char *text)
  17. {
  18. // If the output is piped, the colors don't make much sense
  19. if (!(isatty(STDOUT_FILENO))) {
  20. printf("%s", text);
  21. return;
  22. }
  23. // Normal operation
  24. if (text) {
  25. for (int i = 0; i < strlen(text); ++i) {
  26. int color = 0;
  27. do {
  28. color = rand() % 6;
  29. } while (color == lastcolor);
  30. lastcolor = color;
  31. printf("%s%c", colors[color], text[i]);
  32. }
  33. }
  34. printf("%s", KWHT); // reset to default colors
  35. }
  36. const int BUF_SIZE = 10;
  37. int main(int argc, char *argv[])
  38. {
  39. srand(time(NULL));
  40. char *buffer = malloc(BUF_SIZE);
  41. if (!buffer) {
  42. fprintf(stderr, "Error: out of memory\n");
  43. }
  44. for (int i = 0; i < argc; ++i) {
  45. if (strcmp(argv[i], "-") == 0 || argc == 1) {
  46. while (fgets(buffer, BUF_SIZE, stdin) != NULL) {
  47. printColors(buffer);
  48. }
  49. clearerr(stdin);
  50. } else if (i >= 1) {
  51. FILE *fp;
  52. fp = fopen(argv[i], "r");
  53. if (fp) {
  54. size_t got;
  55. while ((got = fread(buffer, 1, BUF_SIZE -1, fp))) {
  56. buffer[got] = '\0';
  57. printColors(buffer);
  58. }
  59. printf("%s", KWHT);
  60. if (ferror(fp))
  61. fprintf(stderr, "Error: can't read %s\n", argv[1]);
  62. fclose(fp);
  63. } else {
  64. printf("rccat: %s: no such file or directory.\n", argv[1]);
  65. }
  66. }
  67. }
  68. free(buffer);
  69. return 0;
  70. }