Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gotoxy() implementation for Linux using printf

Tags:

c

printf

I was looking for a substitute of gotoxy() for gcc compiler and found this -

void gotoxy(int x,int y)
{
    printf("%c[%d;%df",0x1B,y,x);
}

I want to know how is it functioning, I mean when do we use [ and ; inside printf, what is 0x1B doing there and how does it take the cursor to the row/column with this code?

I have never seen this type of practice for printf in books,so it would be great If you could point me to a link where I can find about such uses of printf.

like image 324
Gaurav Butola Avatar asked Dec 30 '11 20:12

Gaurav Butola


1 Answers

This is using terminal escape codes to position the cursor.

"\x1B" is the escape character that tells your terminal that what comes next is not meant to be printed on the screen, but rather a command to the terminal (or most likely terminal emulator)

The trailing 'f' indicates that you want to force the cursor position somewhere, indicated by the coordinates that precede it.

Force Cursor Position   <ESC>[{ROW};{COLUMN}f

So if you call gotoxy(4,2), it ends up sending the escape sequence "(ESC)[2;4f" where ESC is the byte 0x1B.

like image 86
Jonathon Reinhart Avatar answered Sep 23 '22 02:09

Jonathon Reinhart