lolcat in c
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.
 
 

107 lines
2.3 KiB

#include "colours/colours.h"
#include <getopt.h>
#include <stdbool.h>
#define READ_BUFFER_SIZE 200
/*
* Basic Settings
*/
int rainbow_len = 80; // how many characters long is one full rainbow (360deg)
int col_change; // how many degrees between colours in the rainbow
int col_dist; // how many characters per colour in output
struct colour* colours; // the rainbow
int num_colours; // the length of the rainbow
/* Print the nth colour of the <rainbow_len> rainbow */
void print_next_colour(int current) {
if (current % col_dist == 0) {
struct colour c = colours[(current % num_colours) / col_dist];
c = get_rgb(c);
printf("\x1b[38;2;%d;%d;%dm", c.r, c.g, c.b);
}
}
int display(FILE *file) {
char c = fgetc(file);
int counter = 0;
while (c != EOF) {
if (c == '\n') {
counter = 0;
}
print_next_colour(counter);
printf("%c", c);
counter++;
c = fgetc(file);
}
return 0;
}
int open_and_cat(char *file_name) {
FILE *file = fopen(file_name, "r");
if (!file) {
return 1;
}
return display(file);
}
int generate_rainbow() {
if (rainbow_len < 360) {
num_colours = rainbow_len;
col_change = 360 / num_colours;
if (col_change == 0) {
col_change = 1;
}
} else {
num_colours = 360;
col_change = 1;
}
col_dist = rainbow_len / num_colours;
colours = calloc(num_colours, sizeof(struct colour));
struct colour c;
c.h = 0;
c.s = 1;
c.v = 1;
c.sp = CS_HSV;
for (int i = 0; i < num_colours; i++) {
c.h = (int)(c.h + col_change) % 360;
colours[i] = c;
}
return 0;
}
int main(int argc, char** argv) {
int opt;
int optcount = 0;
while ((opt = getopt(argc, argv, "l:")) != -1) {
optcount++;
if (opt == 'l') {
optcount++;
rainbow_len = atoi(optarg);
} else {
printf("Usage: colcat -l [rainbow length]");
}
}
generate_rainbow();
if (argc > optcount + 1) {
for (int i = 1; i < argc; i++) {
int err = open_and_cat(argv[i]);
if (err) {
perror("Unable to open file");
exit(err);
}
}
} else {
display(stdin);
}
}