大家好,我是一名初学者 C 程序员,当我编写一个简单的终端 watch 时,我注意到我的代码的执行顺序有问题:我运行程序时不显示时间,首先光标闪烁约 3 秒钟,然后显示时间。这是我的代码:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 10
int main(int argc, char** argv)
{
time_t t;
size_t sz;
clock_t now;
struct tm* tm;
static char strtm[BUFSIZE];
while (1)
{
now = clock();
t = time(NULL);
tm = gmtime(&t);
sz = strftime(strtm, sizeof(strtm), "%T", tm);
#if 1
for (;(clock() - now) < (CLOCKS_PER_SEC/3);)
printf("\r");
#endif
printf("%s", strtm);
}
return 0;
}
因此,为了测试程序序列,我编写了以下简单代码,它的行为方式类似。我想让下面的代码做的是
- 显示“1 2 3 4”,
- 将光标移动到'1',
- 等待大约5秒然后退出
但是,它并没有这样做,而是先等待 5 秒,然后才显示“1 2 3 4”
#include <time.h>
#include <stdio.h>
int main()
{
clock_t now = clock();
printf("1 2 3 4");
printf("\r");
for (;(clock() - now) < (5 * CLOCKS_PER_SEC);)
;
return 0;
}
我在 linux 上工作,所以我尝试使用 sleep()
函数,我得到了相同的结果:
#include <unistd.h>
#include <stdio.h>
int main()
{
printf("1 2 3 4");
printf("\r");
sleep(5);
return 0;
}
我需要你帮助我理解我的程序的顺序,因为它似乎在 printf()
之前先运行 for loop/sleep()
函数。非常欢迎指正。谢谢。
最佳答案
您很可能只是看到了输出缓冲的效果。请注意,与 '\n'
不同,'\r'
通常不会刷新输出缓冲区。所以使用 fflush()执行所需的行为,例如
printf("1 2 3 4");
printf("\r");
fflush(stdout);
关于c - 了解使用 for (;clock() - now < CLOCKS_PER_SEC;) 时的程序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33736516/