在基于UNIX的系统上清除C和C++中的屏幕?

12 c unix screen cls

我想知道:如何在基于UNIX的系统上清理屏幕?我在互联网上搜索,但我刚刚在Windows上找到了如何做到这一点:系统("CLS")我不想完全清理屏幕,但我想打开一个"新页面",例如在NANO和VI编辑中.谢谢

Dav*_*eri 21

也许你可以使用转义码

#include <stdio.h>

#define clear() printf("\033[H\033[J")

int main(void)
{
    clear();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但请记住,此方法与所有终端都不兼容

  • [ANSI/VT100终端控制转义序列](http://www.termsys.demon.co.uk/vtansi.htm) (7认同)

Sha*_*har 15

您可以使用以下代码将termcap用于清除屏幕.(别忘了链接到图书馆)

#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>

void clear_screen()
{
char buf[1024];
char *str;

tgetent(buf, getenv("TERM"));
str = tgetstr("cl", NULL);
fputs(str, stdout);
} 
Run Code Online (Sandbox Code Playgroud)

  • +1,在Debian上你必须安装`libncurses5-dev`并使用`-lncurses`编译 (3认同)

Naf*_*ffi 6

#include <stdlib.h>
int main(void)
{
    system("clear");
}
Run Code Online (Sandbox Code Playgroud)


pax*_*blo 5

便携式 UNIX 代码应该使用 terminfo 数据库进行所有光标和屏幕操作。这就是库喜欢curses用来实现窗口等效果的东西。

terminfo 数据库维护了一个功能列表(就像clear您用来清除屏幕并将光标发送到顶部的列表一样)。它为各种设备保持了这样的功能,因此您不必担心您使用的是 Linux 控制台还是(非常过时的)VT52 终端。

至于如何获取某些操作的字符流,您可以选择历史悠久但相当可怕的方法system来执行它:

system ("tput clear");
Run Code Online (Sandbox Code Playgroud)

或者您可以将该命令的输出捕获到缓冲区,以便以后使用仅涉及输出字符而不是重新运行命令:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static char scrTxtCls[20]; static size_t scrSzCls;

// Do this once.

FILE *fp = popen ("tput clear", "r");
scrSzCls = fread (scrTxtCls, 1, sizeof(scrTxtCls), fp);
pclose (fp);
if (scrSzCls == sizeof(scrTxtCls)) {
    actIntelligently ("you may want to increase buffer size");
}

// Do this whenever you want to clear the screen.

write (1, cls, clssz);
Run Code Online (Sandbox Code Playgroud)

或者,您可以链接ncurses并使用它的 API 来获得您想要的任何功能,尽管这可能会为清除屏幕等简单的事情带来很多东西。尽管如此,它仍然是一个值得认真考虑的选项,因为它为您提供了更多的灵活性。


Bas*_*tch 3

这通常不仅仅是清除屏幕的问题,而是制作终端感知应用程序的问题。

您应该使用ncurses库并阅读NCURSES 编程指南

(你也许可以使用一些ANSI 转义码,正如David RF回答的那样,但我认为这不是一个好主意)