Francesco Frassinelli
Francesco Frassinelli

Reputation: 3385

Get in which terminal column I'm writing

In my C program I would like to know where my cursor is located in terminal. For example, another program could have written something before mine and I would like to know how much space is left before the last column of the terminal, or I could not know the terminal reaction to some special sequences (like colors: I could write it but they are not showed).

Any suggestion?

Edit: it would be better avoiding over complicated solutions like ncurses (ncurses doesn't know where's the cursor directly: it computes its position).

Edit 2: I found a way to do it, but it works only in non-graphical terminals: https://www.linuxquestions.org/questions/programming-9/get-cursor-position-in-c-947833/

Edit 3: Nice code and it works well, but it uses /dev/vcsaN (same problem of Edit 2): http://dell9.ma.utexas.edu/cgi-bin/man-cgi?vcs+4

Upvotes: 1

Views: 470

Answers (4)

LeoNerd
LeoNerd

Reputation: 8532

Generally you are supposed to remember where you've left the cursor.

However, most terminals do respond to DSR; Device Status Request. By sending

CSI 6 n

you'll receive a CPR; cursor position report, in the form of

CSI Pl;Pc R

where Pl and Pc give the cursor line and column number, indexed from 1.

Upvotes: 0

Francesco Frassinelli
Francesco Frassinelli

Reputation: 3385

This solution is not optimal because it refers to /dev/vcsa*. Hope this could help someone else.

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main(void)
{
    int fd;
    char *device = "/dev/vcsa2";
    struct {unsigned char lines, cols, x, y;} scrn;
    fd = open(device, O_RDWR);
    if (fd < 0) {
        perror(device);
        exit(EXIT_FAILURE);
    }
    (void) read(fd, &scrn, 4);
    printf("%d %d\n", scrn.x, scrn.y);
    exit(EXIT_SUCCESS);
}

Upvotes: 0

n. m. could be an AI
n. m. could be an AI

Reputation: 120049

Ncurses is a big and powerful library for creating terminal-based text interfaces.

tputs is a simple low-level universal function for manipulating terminal capabilities.

Either one could serve your needs.

Upvotes: 2

NPE
NPE

Reputation: 500803

You could try using ncurses' getyx().

Upvotes: 1

Related Questions