I make the follow screensaver-program. I using ANSI codes, for clear the screen of terminal and define the position of current time. However, many times printed the same ANSI codes. For example in line:
printf( "\e[%d;%df%s\n", random_line, random_column, ctime( &t1 ));
printed -->
[0;-14fMon Jun 1 13:39:49 2015
my code is:
#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 );
}
The ANSI escape sequence is not well formed when you provide a negative value for either row or column, which is why you're seeing something like:
[0;-14fMon Jun 1 13:39:49 2015
rather than the string:
Mon Jun 1 13:39:49 2015
positioned somewhere.
Basically, the ANSI sequence interpreter has no idea how to place the cursor fourteen character to the left of the leftmost side of your screen, so you should probably revisit why you're subtracting 20 from the random value to get the column.
If it's to ensure the text fits on the line chosen without wrapping to the next line, you should instead use (changing the value as well since there's more than 20 characters in your date string):
random_column = rand() % (columns - 25);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With