暂停并重新启动终端输出

时间:2014-03-17 02:24:36

标签: c io terminal sleep backspace

我尝试做的是让终端打印出一个字符串,暂停,然后在该字符串上写字。然而,正在发生的事情是程序只打印出最终结果,而不显示第一个字符串。

我以为我可以使用sleep来执行此操作,但它无法正常工作。为什么不呢?

#include <stdio.h>
#include <unistd.h>

int main(void){

    char message[] = "Hello there";
    int messageLength = sizeof(message);
    int i;

    printf("Hello, Dave.");
    sleep(2);
    for(i = 0; i < messageLength; i++)
        printf("\b");
    printf("Anyone there?\n");

    return 0;

}

更新版本,感谢答案:

#include <stdio.h>
#include <unistd.h>
#include <time.h>

void twprint(char* output, int outputLength, struct timespec* delay);
void twbackspace(int length, struct timespec* delay);

int main(void){

    char message1[] = "Hello, Dave.";
    char message2[] = "Are you there, Dave?";
    char message3[] = "I heard you talking in the pod.";
    char message4[] = "Dave?";
    struct timespec duration = { .tv_sec = 0, .tv_nsec = (100 * 1000 * 1000) }; 
    /* ^ .tv_nsec = one hundred million nanoseconds */

    twprint(message1, sizeof(message1)/sizeof(char), &duration);
    sleep(2);
    twbackspace(sizeof(message1)/sizeof(char), &duration);

    twprint(message2, sizeof(message2)/sizeof(char), &duration);
    sleep(2);
    twbackspace(sizeof(message2)/sizeof(char), &duration);

    twprint(message3, sizeof(message3)/sizeof(char), &duration);
    sleep(2);
    twbackspace(sizeof(message3)/sizeof(char), &duration);

    sleep(2);
    duration.tv_nsec *= 5;
    twprint(message4, sizeof(message4)/sizeof(char), &duration);

    printf("\n");

    return 0;

}

void twprint(char* output, int outputLength, struct timespec* delay){

    int i;
    struct timespec remaining; /* dummy parameter */

    for(i = 0; i < outputLength; i++){
        printf("%c", output[i]);
        fflush(stdout);
        nanosleep(delay, &remaining);
    }

}

void twbackspace(int length, struct timespec* delay){

    int i;
    struct timespec remaining; /* dummy parameter */

    for(i = 0; i < length; i++){
        printf("\b \b");
        fflush(stdout);
        nanosleep(delay, &remaining);
    }
}

2 个答案:

答案 0 :(得分:3)

printf的输出被缓冲并且不会被打印到控制台,直到缓冲区已满,您打印换行符或调用fflush(标准输出)。尝试:

...
printf("Hello, Dave.");
fflush(stdout);
sleep(2);
...

维基百科提供a good explanation标准流及其在缓冲方面的行为。

答案 1 :(得分:1)

您需要刷新输出流才能显示该行:

printf("Hello, Dave.");
fflush(stdout);

顺便说一句,正常情况下,控制台输出会转到stderr。如果你这样做,你就不必担心刷新(在许多平台上),因为stderr通常是无缓冲的(因此输出是立即的),而stdout通常是行缓冲的(因此输出不会直到你写一个换行符才会出现。)

相关问题