2

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

示例:如果我尝试打印一个包含 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
4

1 回答 1

0

这是解决方案:

#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;
}
于 2015-10-28T15:43:47.667 回答