summaryrefslogtreecommitdiff
path: root/rccat.c
blob: 1c31e38d4951790df2551e4de6a1ced565b7bcc0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/* ~\~ language=C filename=rccat.c */
/* ~\~ begin <<rccat.md|rccat.c>>[0] */
/* ~\~ begin <<rccat.md|includes>>[0] */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
/* ~\~ end */

/* ~\~ begin <<rccat.md|constants>>[0] */
#define BUF_SIZE 10

/* ~\~ begin <<rccat.md|colors>>[0] */
#define KNRM "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"

const char *colors[] = {KNRM, KRED, KGRN, KYEL, KMAG, KCYN};
/* ~\~ end */
/* ~\~ end */

/* ~\~ begin <<rccat.md|colors-function>>[0] */
int lastcolor = 0;
void printColors(char *text)
{
	/* ~\~ begin <<rccat.md|colors-notty>>[0] */
	if (!(isatty(STDOUT_FILENO))) {
		printf("%s", text);
		return;
	}
	/* ~\~ end */
	if (text) {
		/* ~\~ begin <<rccat.md|colors-normal>>[0] */
		for (int i = 0; i < strlen(text); ++i) {
			int color = 0;
			do {
				color = rand() % 6;
			} while (color == lastcolor);
			lastcolor = color;
			printf("%s%c", colors[color], text[i]);
		}
		/* ~\~ end */
	}
	/* ~\~ begin <<rccat.md|colors-reset>>[0] */
	printf("%s", KWHT);
	/* ~\~ end */
}
/* ~\~ end */

/* ~\~ begin <<rccat.md|main-function>>[0] */
int main(int argc, char *argv[])
{
	/* ~\~ begin <<rccat.md|main-body>>[0] */
	srand(time(NULL));
	char buffer[BUF_SIZE] = {""};

	for (int i = 0; i < argc; ++i) {
		/* ~\~ begin <<rccat.md|parse-arg>>[0] */
		if (strcmp(argv[i], "-") == 0 || argc == 1) {
			/* ~\~ begin <<rccat.md|print-from-stdin>>[0] */
			while (fgets(buffer, BUF_SIZE, stdin) != NULL) {
				printColors(buffer);
			}
			clearerr(stdin);
			/* ~\~ end */
		} else if (i >= 1) {
			/* ~\~ begin <<rccat.md|open-file>>[0] */
			FILE *fp;
			fp = fopen(argv[i], "r");
			if (!(fp)) {
				fprintf(stderr, "rccat: %s: no such file or directory.\n", argv[i]);
			}
			/* ~\~ end */
			/* ~\~ begin <<rccat.md|read-file>>[0] */
			size_t got;
			while ((got = fread(buffer, 1, BUF_SIZE -1, fp))) {
				buffer[got] = '\0';
					printColors(buffer);
				}
				if (ferror(fp))
					fprintf(stderr, "Error: can't read %s\n", argv[1]);
			/* ~\~ end */
			/* ~\~ begin <<rccat.md|close-file>>[0] */
			fclose(fp);
			/* ~\~ end */
		}
		/* ~\~ end */
	}
	/* ~\~ end */

	return EXIT_SUCCESS;
}
/* ~\~ end */
/* ~\~ end */