2

テキストを表示するマクロを作成し、その後 stdout をフラッシュします。問題は、テキストが新しいものよりも長い場合に、古い印刷テキストを強制的に消去する方法です。

例 : その後 50 文字の文字列を印刷しようとすると、すべてのテキストを上書きし、テキストを 25 文字で書き直す必要があります。2 番目のテキストの方が短いため、常に最初のテキストの一部が常に印刷されます。

\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 に答える