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

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;
}