Using ANSI Codes in a C Program

I am making the following screensaver program. I am using ANSI codes to clear the terminal screen and determine the position of the current time. However, the same ANSI codes have been printed many times. For example, in the line:

printf( "\e[%d;%df%s\n", random_line, random_column, ctime( &t1 ));

      

printed →

[0; -14fMon Jun 1 13:39:49 2015

my code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>

int main( void )
{
    int lines = 0, columns = 0, random_line = 0, random_column = 0;
    time_t t1;
    struct winsize w;

    while( 1 )
    {
        printf( "\e[2J\n" );

        ioctl( 0, TIOCGWINSZ, &w );
        //printf( "Lines of Term: %d\n", w.ws_row );
        //printf( "Columns of Term: %d\n", w.ws_col );
        lines = w.ws_row;
        columns = w.ws_col;

        srand( time( NULL ) );
        random_line = rand() % lines;
        //printf( "Random Line = %d\n", random_line );
        random_column = ( rand() % columns ) - 20;
        //printf( "Random Column = %d\n", random_column );

        t1 = time( NULL );
        printf( "\e[%d;%df%s\n", random_line, random_column, ctime( &t1 ) );
        sleep( 5 );
    }

    return ( 0 );
}

      

+3


source to share


1 answer


An ANSI escape sequence is not formed when you specify a negative value for a row or column, so you see something like:

[0;-14fMon Jun 1 13:39:49 2015

      

not the line:

Mon Jun 1 13:39:49 2015

      



located somewhere.

Basically, the ANSI sequence interpreter has no idea how to position the fourteen character cursor to the left of the left side of the screen, so you should probably reconsider why you are subtracting 20

from a random value to get a column.

If it is necessary for the text to match the selected line without breaking to the next line, you should instead use (change the value since the date string has more than 20 characters):

random_column = rand() % (columns - 25);

      

+1


source







All Articles