简体   繁体   English

如何使用C清除Linux终端中的先前输出?

[英]how to clear my previous output in Linux terminal using C?

This is my sample program for simulating a Loading progress. 这是我的用于模拟加载进度的示例程序。 The only problem I'm facing right now is clearing my previous output of "Loading: %i" 我现在面临的唯一问题是清除以前的输出“ Loading:%i”

/* loading program */

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

#define TIMELIMIT 5

int main()
{
    for(int i = 0, j; i < 5; ++i) {
        j = i;
        printf("Loading: %i%%", ++j);
        sleep(1);
    //system("bash -c clear");    not working
    //printf("\033[2J\033[1;1H"); clears whole screen with no output at all
    }
    return(0);
}

if you print \\r instead of \\n using printf , then it will return to the beginning of the same line instead of the next line. 如果使用printf打印\\r而不是\\n ,则它将返回到同一行的开头,而不是下一行。 Then you can re-print the new status on top of the old line. 然后,您可以在旧行的顶部重新打印新状态。

Anyway here is the correct code. 无论如何,这里是正确的代码。 Thanks to Mobius and Dmitri. 感谢Mobius和Dmitri。

/* loading program */

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

#define TIMELIMIT 5

int main()
{
    for(int i = 0, j; i < TIMELIMIT; ++i) {
        j = i;
        printf("Loading: %i%%", ++j);
        printf("\r");
        fflush(stdout);
        sleep(1);
    }
    return(0);
}

I think the answer to this question is system("reset"). 我认为这个问题的答案是system(“ reset”)。 This is the command you're looking for 这是您要查找的命令

    reset

this command clears your whole terminal. 此命令清除整个终端。

and your code go like this, 你的代码就这样,

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

#define TIMELIMIT 5

int main()
{
    int i,j;
    for(int i = 0, j; i < 5; ++i) {
        j = i;
        system("reset");
        printf("Loading: %i%%\n", ++j);
        sleep(1);
    //system("bash -c clear");    not working
    //printf("\033[2J\033[1;1H"); clears whole screen with no output at all
    }
    return(0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM