Text-cursor position handling in C (under Linux)

Viewed 361

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("\u2554\u2550\u2550\u2550\u2557\n\u255A\u2550\u2550\u2550\u255D\n");
    }
}

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?

2 Answers

[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)

Write \033[H to the console, and this will put the cursor in the top left corner of the terminal.

For that, the terminal must be ANSI compatible (for example, the xterm terminal or the linux console)

Anyway, I recommend you to use the ncurses library, which gives you many possibilities, apart of this, and in a manner that is terminal type independent (so it will run in almost any known terminal type, e.g. an hp terminal)

Related