开发者

Clear part of terminal screen in C++ unix?

I want to output stuff onto the terminal window and then only clear part of it (like first half or quarter etc) and not the rest. Is there a way I can do this? I was开发者_开发知识库 using system("clear"), but that clears everything. I'd prefer to NOT use ncurses. Any help is appreciated.


If you need a general solution, then it will somehow involve going back in the terminal, by using special characters, overwrite the part that you want to delete with blanks and restore the part, that should still be visible.

You can find out, how to go back in the terminal in this post. It includes some examples, that show how to use the carriage return (\r) character.

Furthermore there is also an example, that shows how to use ansi escape sequences to get red text. In the same way, you can write to a specific position on the terminal using ansi escape sequences, take a look here. "Force Cursor Position" in this link should give you the ability to write blank spaces to every position, you want to clear.

However you should be aware, that not all terminals support these methods and that if you stream your output to a file, it will contain those special characters.


If you work out what the capabilities of your terminal are, you can simply write them to stdout with cout.

If you're not sure where to start, you can experiment like this: At the prompt, type man terminfo and you may get a list of terminal capabilities. Try them out with tput to see which ones work. Then figure out what the codes you need to print are with something like:

% tput el | od -t x1 
0000000    1b  5b  4b                                                    
0000003

Sending these bytes to my terminal issues "clr_eol" ("el") which clears to the end of the line. Work out how to move the cursor around on your terminal, how to clear lines, and you're done.

Seeing as you're using gnome-terminal you can do this to erase the top 3 lines: move the cursor to home, erase to end of line, move down, erase to end of line, move down, erase to end of line.

To figure out what you need to print:

% ( tput home ; tput el ; tput cud1 ; tput el ; tput cud1 ; tput el ; tput cud1 ; tput el ; tput cud1 ; tput el ) | od -t x1
0000000    1b  5b  48  1b  5b  4b  0a  1b  5b  4b  0a  1b  5b  4b  0a  1b
0000020    5b  4b  0a  1b  5b  4b                                        
0000026

Sending those bytes (1B 5B 48 etc.) to stdout (with cout) will do the trick from C++.

Using ncurses will be more portable, if you don't want to use it you may find you're eventually reimplementing it.


There are two VT100 escape sequences for clearing from the cursor and up/down to the top/bottom of the screen, respectively.

See http://www.termsys.demon.co.uk/vtansi.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜