17

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

4

10 回答 10

23

也许您可以使用转义码

#include <stdio.h>

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

int main(void)
{
    clear();
    return 0;
}

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

于 2013-06-24T09:00:40.900 回答
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);
} 
于 2013-06-24T09:10:43.793 回答
6

可移植的 UNIX 代码应该使用 terminfo 数据库进行所有光标和屏幕操作。这就是库喜欢curses用来实现窗口等效果的方法。

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

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

system ("tput clear");

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

#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);

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

于 2013-06-24T09:12:15.903 回答
6
#include <stdlib.h>
int main(void)
{
    system("clear");
}
于 2013-06-24T09:16:24.640 回答
3

通常不仅仅是清除屏幕,而是制作一个终端感知应用程序。

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

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

于 2013-06-24T08:59:54.183 回答
3

您可以使用 CSI 序列来实现此目的:

#include <stdio.h>
int main()
{
    printf("\x1b[H\x1b[J");
}

有什么作用\x1b[H

其实和 一样\x1b[1;1;H,就是将光标移动到第 1 行第 1 列。

\x1b[J又是什么\x1b[0;J

如果 n 为 0 或缺失,它将从光标到屏幕末尾清除。

来源:https ://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences

于 2018-05-23T07:46:57.923 回答
2

#include<stdlib.h>之后使用#include<stdio.h>

然后就可以使用后面的命令system("clear");main() {

IE:

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

int main()
{
    system("clear");

在这些命令之后,您可以继续您的程序。

希望这可以帮助 :)

于 2017-09-24T12:12:54.280 回答
1

要使用 termcaps 清除屏幕,请使用以下命令:

write(1, tgetstr("cl", 0), strlen(tgetstr("cl", 0)));
于 2014-09-09T09:00:17.263 回答
1

system("clear");与标头一起使用#include <stdlib.h>(对于 C 语言)或#include <cstdlib>(对于 C++)。

于 2017-11-08T18:22:49.817 回答
0

此代码用于在终端样式窗口中重置滚动条位置的清晰屏幕

#include <iostream>

int main(){
   std::cout << "\033c";
   return 0;
}
于 2018-12-25T20:43:14.513 回答