C 中的“\r”在它之前停止输出

"\r" in C stops output before it

我写了一段这样的代码:

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

int main() {
    printf("one");
    sleep(1);
    printf("\r");
    printf("two");
    return 0;
}

本来应该先打印“一”,然后在停顿一秒后用“二”覆盖它。

但真正发生的是它只在一秒空后打印“二”,而不是先打印“一”。我很困惑,有人可以弄清楚吗?非常感谢。

语句printf("one")不是立即向终端打印“one”,而是将字符串写入标准输出流(stdout) - 通常是缓冲的。只有当这个流被刷新时,它的内容才会打印到终端。通常,每当打印换行符或程序退出时,除其他情况外,都会发生这种情况。

可以通过调用 fflush(stdout) 强制刷新输出流,从而产生所需的结果:

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

int main(void) {
    printf("one");
    fflush(stdout); // Line added
    sleep(1);
    printf("\r");
    printf("two");
    return 0;
}

参见fflush for more information. The buffering mode of a stream can be set using the setvbuf函数。

此外,请注意,通常的 main 签名在不使用参数时是 int main(void).

致谢:感谢Andreas Wenzel的更正和setvbuf的补充。