今天整理文件发现一个隐藏在硬盘角落里的一段神秘代码,运行之后发现这是一断让我打开眼界的程序。

#include <stdio.h>
#include <unistd.h>
int main()
{
    int i;
    for(i=0;i<=100;i+=10)
    {
        printf("Percent completed:%3d%%\r",i);
        sleep(1);
       fflush(stdout);
    }
}

我们先在终端中运行该程序:
gcc -o func func.c
./func
程序会在同一行文件中打印 Percent completed:0% 10%……100%
对于这段神秘的代码,有两个需要注意的地方第一是printf中的\r,第二是fflush(stdout).

将\r换成\n

首先我们将\r换成\n,运行代码查看效果.
打印如下:
Percent completed:0%
Percent completed:10%
Percent completed:20%
Percent completed:30%
Percent completed:40%
Percent completed:50%
Percent completed:60%
Percent completed:70%
Percent completed:80%
Percent completed:90%
Percent completed:100%
这究竟是为什么呢?
经过查找C相关书籍终于在一本泛黄的书中某个角落里看到歪歪斜斜写着两行字:
\r 转义序列。表示carriage return(回车键)
\n是另起一行,\r的话回车回到本行的开头,如果继续输入的话会把先前的覆盖掉
原来竟是如此,\r自己很少使用.

注释掉fflush(stdout)

如果我们注释掉fflush(stdout)会有什么反应呢?
实践发现,注释掉fflush(stdout)之后程序运行一片空白.
在StackOverflow中看到如下解释:
You would use fflush(stdout) to ensure that whatever you just wrote in a file/the console is indeed written out on disk/the console.
The reason is that actually writing, whether to disk, to the terminal, or pretty much anywhere else, is pretty slow. Further, writing 1 byte takes roughly the same time as writing, say, a few hundred bytes[1]. Because of this, data you write to a stream is actually stored in a buffer which is flushed when it is full or when you call fflush. Calling fflush means you are accepting that your function call will take a bit of time but that you are 100% sure that you want this out right away.
至此我们可以看到在短短的几行代码中竟隐藏着这么多知识点.