Linux中gotoxy函数的一个实现

摘自:Linux: gotoxy() – C

Linux中要移动光标一般要用到ncurses库中的move函数,这里找到一个纯C实现的gotoxy函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <string.h>

void clrscr(void) {
    int i;

    for (i = 0; i < 100; i++)
        // A bunch of new lines for now. It's blank, hey!
        putchar('\n');
}

int gotoxy(int x, int y) {
    char essq[100];     // String variable to hold the escape sequence
    char xstr[100];     // Strings to hold the x and y coordinates
    char ystr[100];     // Escape sequences must be built with characters

    /*
    ** Convert the screen coordinates to strings
    */

    sprintf(xstr, "%d", x);
    sprintf(ystr, "%d", y);

    /*
    ** Build the escape sequence (vertical move)
    */

    essq[0] = '\0';
    strcat(essq, "\033[");
    strcat(essq, ystr);

    /*
    ** Described in man terminfo as vpa=\E[%p1%dd
    ** Vertical position absolute
    */

    strcat(essq, "d");
   
    /*
    ** Horizontal move
    ** Horizontal position absolute
    */

    strcat(essq, "\033[");
    strcat(essq, xstr);
    // Described in man terminfo as hpa=\E[%p1%dG
    strcat(essq, "G");

    /*
    ** Execute the escape sequence
    ** This will move the cursor to x, y
    */

    printf("%s", essq);

    return 0;
}

/*
** Example
*/

int main () {
    clrscr();
    gotoxy(2, 0);
    printf("Coordinates: x = 2; y = 0;\n");
    gotoxy(5, 5);
    printf("Coordinates: x = 5; y = 5;\n");

    return 0;
}
更多
One Response Post a comment

Leave a Reply

Note: You may use basic HTML in your comments. Your email address will not be published.

Subscribe to this comment feed via RSS