Console in windows and linux
阿新 • • 發佈:2020-08-11
On windows, it prvoides the API to get and set cursor functions.
#include <windows.h> COORD GetCursorPosition() { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO bufferInfo; GetConsoleScreenBufferInfo(h, &amp;bufferInfo); return bufferInfo.dwCursorPosition; }void SetCursorPosition(int XPos, int YPos) { COORD coord; coord.X = XPos; coord.Y = YPos; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord); }
in Linux, it does not provide the API, but it can be got/set by ESC code.
#include <stdio.h> void SetCursorPosition(int XPos, intYPos) { printf("\033[%d;%dH",YPos+1,XPos+1); } void getCursor(int* x, int* y) { printf("\033[6n"); /* This escape sequence !writes! the current coordinates to the terminal. We then have to read it from there, see [4,5]. Needs <termios.h>,<unistd.h> and some others*/ scanf("\033[%d;%dR", x, y); }
other ESC strings can be found athttp://ascii-table.com/ansi-escape-sequences.php
Some examples are provided below.
- Position the Cursor:
\033[<L>;<C>H
Or
\033[<L>;<C>f
puts the cursor at line L and column C.
- Move the cursor up N lines:
\033[<N>A
- Move the cursor down N lines:
\033[<N>B
- Move the cursor forward N columns:
\033[<N>C
- Move the cursor backward N columns:
\033[<N>D
- Clear the screen, move to (0,0):
\033[2J
- Erase to end of line:
\033[K
- Save cursor position:
\033[s
- Restore cursor position:
\033[u