Skip to content
Advertisement

Text-cursor position handling in C (under Linux)

I’m trying to reposition the text-cursor to top left corner of the console each frame, so the resulted square rendered at the same position

#include <stdio.h>
#include <stdlib.h>

int main() {
    while(1) {
        printf("u2554u2550u2550u2550u2557nu255Au2550u2550u2550u255Dn");
    }
}

I found that this is possible in windows by including <windows.h>:

HANDLE hOut;
    COORD Position;
    hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    Position.X = 0;
    Position.Y = 0;
    SetConsoleCursorPosition(hOut,Position);

How can I do that in Ubuntu?

Advertisement

Answer

[update] Oops, sorry, I didn’t notice the “[C]” tag and my answer was only referring to shell commands.

The actual answer is to use a curses-like library, like ncurses.

For example, the function you are looking for is typically move().


Original answer:

On Unix systems, moving the cursor depends on the type of the terminal you are using.

There are libraries like ncurses that aim to provide functionalities that are terminal-independent. tput is a command that uses ncurses to make some terminal capabilities (like moving the cursor) available to the command line:

tput cup 0 0

will put the cursor in the (0,0) position, whatever the terminal you are using (if such a terminal allows you to move the cursor)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement