繁体   English   中英

如何从标准输出中删除显示的文本?

[英]How remove displayed text from stdout?

我创建了一个显示文本的宏,然后将其刷新标准输出。 问题是如果文本比新文本更长,如何强制清除旧的打印文本。

示例:如果之后尝试打印包含50个字符的字符串,则需要覆盖所有文本并重写具有25个字符的文本。 一直以来,我始终会打印第一个文本的一部分,因为第二个文本更短。

我还需要在每行的末尾插入\\r ,如何在宏中添加?

#include <stdio.h>
#include <string.h>
// I need to add "\r" to macro instead of to add it for all string
#define MESSAGE( fmt, args...) \
    do { setbuf(stdout, NULL); fprintf(stdout, fmt, ## args); fflush(stdout); sleep(5); } while (0)

int main()
{
    MESSAGE( "the application is started successfully\r");
    MESSAGE( "the application will be stopped soon\r");
    MESSAGE( "app stopped: ok\n\r");
    return 0;
}

结果:

./test2
app stopped: ok will be stopped soonlly

预期结果:

./test2
app stopped: ok

这是解决方案:

#include <stdio.h>
#include <string.h>

#define MESSAGE( fmt, args...) \
    do { fprintf(stdout, fmt, ## args); fprintf(stdout, "\r"); fflush(stdout); sleep(1); fprintf(stdout, "\x1b[2K"); } while (0)

int main()
{
    MESSAGE( "the application is started successfully");
    MESSAGE( "the application will be stopped soon");
    MESSAGE( "app stopped: ok");
    return 0;
}

暂无
暂无

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

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