Removing ANSI escape sequences from a string, C

153 Views Asked by At

I've been making a lolcat-alike program in C - think the unix cat utility, but it formats input to rainbowed text (the original is made in Ruby, which I found to be a little unnecessarily bloated for such a simple command, so I decided to rewrite it in C). Worked out how to use escape sequences and all that. Having some difficulty removing them, though.

Here is my current code:

#include <stdio.h>
#include <string.h>

void prntcol(char c, int r, int g, int b) {
    printf("\x1b[38;2;%d;%d;%dm%c\x1b[0m", r, g, b, c);
}

void processLine(const char *line) {
    int i = 0;

    while (line[i] != '\0') {
        if (line[i] == '\x1b' && line[i + 1] == '[') {
            while (line[i] != '\0' && line[i] != 'm') {
                i++;
            }
            if (line[i] == 'm') {
                printf("\x1b[0m"); 
                i++;
            }
        } else if (line[i] == '\n') {
            printf("\n");
        } else {
            prntcol(line[i], 255, 0, 0);
        }
        i++;
    }
}


int main() {
    char buffer[BUFSIZ];

    while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        processLine(buffer);
    }

    return 0;
}

You see, in order to print the output as ANSI-colored text, the input has to be filtered first, otherwise the already-present escape sequences will mess with the new ones. But if you actually run the program you will see that the function to do that is kinda scuffed. I just can't seem to work out how to actually filter it, and a bunch of things end up getting through. I just feel like there has to be a better way, I just can't seem to figure it out.

0

There are 0 best solutions below