Print character at coordinates in C

1.3k views Asked by At

I wanted to write a vi-like text editor for Linux in C (just as a personal exercise) and I realized that it would be really useful if I could print a character in a precise position in C. Is there a function from the standard library that accomplishes this? Something like:

int PrintAt(int x, int y, char c);
1

There are 1 answers

4
AMZG studio's On

A simple way to do this would be to use ANSI escape sequences. there is a sequence that moves the cursor to a XY position, and then you can print things over there.

the escape sequence looks like this: \033[x;yH x and y being the location, so to easily move the location, you can define a simple macro that will do the trick, or put it in your function.

Macro-way: #define cursorXY(x,y) printf("\033[%d;%dH",(x),(y))

Function-way:

void PrintAt(int x, int y, char c)
{
   printf("\033[%d;%dH%c", x, y, c);
}

(Note the top left corner is (0, 0) on the screen)