很多人估计都有这种需求,使用printf打印输出的时候,可以指定输出在屏幕上的指定位置,这样就可以有“刷屏”的效果了,而不用滚屏。这个东西,使用 ncorses 这个库http://www.gnu.org/s/ncurses/ 应该是可以的了,这个接口作这个应该和你简单啊。不过有人觉得可能有点大材小用了。
其实终端本身也有支持一些特殊的控制字符组合“ ANSI/VT100 Terminal Control Escape Sequences” 参见 这个网站,完整的都到那里去看吧。
摘录一些如下
------------------------------------------
Cursor Control
Cursor Home
Sets the cursor position where subsequent text will begin. If no row/column parameters are provided (ie.
Cursor Up
Moves the cursor up by COUNT rows; the default count is 1.
Cursor Down
Moves the cursor down by COUNT rows; the default count is 1.
Cursor Forward
Moves the cursor forward by COUNT columns; the default count is 1.
Cursor Backward
Moves the cursor backward by COUNT columns; the default count is 1.
Force Cursor Position
Identical to Cursor Home.
Save Cursor
Save current cursor position.
Unsave Cursor
Restores cursor position after a Save Cursor.
Save Cursor & Attrs
Save current cursor position.
Restore Cursor & Attrs
Restores cursor position after a Save Cursor.
-------------------------
Erasing Text
Erase End of Line
Erases from the current cursor position to the end of the current line.
Erase Start of Line
Erases from the current cursor position to the start of the current line.
Erase Line
Erases the entire current line.
Erase Down
Erases the screen from the current line down to the bottom of the screen.
Erase Up
Erases the screen from the current line up to the top of the screen.
Erase Screen
Erases the screen with the background colour and moves the cursor to home.
-----------------------------------
Set Display Attributes
Set Attribute Mode
Sets multiple display attribute settings. The following lists standard attributes:
0 Reset all attributes
1 Bright
2 Dim
4 Underscore
5 Blink
7 Reverse
8 Hidden
Foreground Colours
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White
Background Colours
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White
-------------------------------------------------------
其他的还有滚屏 颜色的控制等
所以,简单的程序使用printf输出这个控制字符序列就可以起到控制光标和清除屏幕的作用了。比如下面这样写:
#include
void main(void) {
printf("dddddddddd1234\n");
printf("%c[%dD",0x1b, 3); //光标后退3个字符
printf("%c[%dA",0x1b, 3); //光标向上移动3行
printf("11111111111111111111111111111111\n");
printf("%c[2J",0x1b); //清除屏幕
printf("%c[32;40m",0x1b); //设置文字颜色为绿色,背景为黑色
printf("绿色的字");
printf("%c[31;42m",0x1b); //设置文字颜色为红色,背景为绿色
printf("红色的字");
}