Clear screen in C and C++ on UNIX-based system?

前端 未结 10 1560
青春惊慌失措
青春惊慌失措 2020-12-08 08:23

I want to know: how to clean screen on an UNIX-based system? I searched on the Internet, but I\'ve just found how to do it on Windows: system(\"CLS\") I don\'t want exactly

相关标签:
10条回答
  • 2020-12-08 09:04

    Just use #include<stdlib.h> after #include<stdio.h>.

    Then you can use the command system("clear");after main() {

    i.e:

    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
        system("clear");
    

    After these commands you can continue with your program.

    Hope this helps :)

    0 讨论(0)
  • 2020-12-08 09:08

    Portable UNIX code should be using the terminfo database for all cursor and screen manipulation. This is what libraries like curses uses to achieve its effects like windowing and so forth.

    The terminfo database maintains a list of capabailities (like clear which is what you would use to clear the screen and send the cursor to the top). It maintains such capabilities for a wide range of devices so that you don't have to worry about whether you're using a Linux console or a (very dated) VT52 terminal.

    As to how you get the character streams for certain operations, you can choose the time-honored but rather horrible method of just using system to do it:

    system ("tput clear");
    

    Or you can capture the output of that command to a buffer so later use involve only outputting the characters rather than re-running the command:

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

    Or, you can link with ncurses and use its API to get whatever capabilities you want, though this might drag in quite a bit of stuff for something as simple as clearing the screen. Still, it's an option to be considered seriously since it gives you a lot more flexibility.

    0 讨论(0)
  • 2020-12-08 09:09

    To clear the screen using termcaps, use this :

    write(1, tgetstr("cl", 0), strlen(tgetstr("cl", 0)));
    
    0 讨论(0)
  • 2020-12-08 09:11

    You can achieve this using CSI sequences:

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

    What does \x1b[H?

    Actually it is the same as \x1b[1;1;H, it means that it will move the cursor to row 1 and column 1.

    What does \x1b[J a.k.a \x1b[0;J?

    If n is 0 or missing, it will clear from cursor to end of screen.

    Source: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences

    0 讨论(0)
提交回复
热议问题