Playing with Text and Animations on Linux Terminal (With VT100 Escape Codes)


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

I am working on a project where I’ll need to do some animations straight in the terminal with ASCII. I believe you can do that in a sophisticated way using the NCurses library, but as usual I want first to see what I can do with bare C functions and syscalls.

I discovered that most terminals support the VT100 escape codes, so that gives you a lot of options.

Here’s a first program that will switch between “HELLO” and “WORLD” five times on the screen and then terminate.


int main(){
        int i,j;

        for(i=0;i<10;i++){
                if(i%2==0){
                        write(1,"HELLO",5);
                }
                else{
                        write(1,"WORLD",5);
                }
                sleep(1);
                /*deletes current line and returns to beginning*/
                write(1,"\33[2K\r",5);
        }
        return 0;

}

And here’s a program that will write “HELLO”, wait 1 second, write “WORLD” on the next line, wait 1 second, then erase both lines and finally write “yeah”.


int main(){
        int i,j;

        write(1,"hello\n",6);
        sleep(1);
        write(1,"world",5);
        sleep(1);
        write(1,"\33[2K\r",5); /*erase line and carriage return*/
        write(1,"\33[1A",4); /*move 1 line up*/
        write(1,"\33[2K\r",5); /*erase line and carriage return*/
        write(1,"yeah\n",5);

        return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *