[英]how to clear my previous output in Linux terminal using C?
这是我的用于模拟加载进度的示例程序。 我现在面临的唯一问题是清除以前的输出“ 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);
}
如果使用printf
打印\\r
而不是\\n
,则它将返回到同一行的开头,而不是下一行。 然后,您可以在旧行的顶部重新打印新状态。
无论如何,这里是正确的代码。 感谢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);
}
我认为这个问题的答案是system(“ reset”)。 这是您要查找的命令
reset
此命令清除整个终端。
你的代码就这样,
#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.