问题描述
我有一个 C 程序,我只是想在其中测试是否可以在安装模块时重现 npm install
中使用的控制台微调器.这个特殊的微调器只是按以下顺序旋转:
I have a C program, where I just wanted to test if I could reproduce a console spinner used in npm install
while it installs a module. This particular spinner simply spins in this order:
|
\
在同一个空间,所以我使用以下程序:
on the same space, so I use the following program:
#include <stdio.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
// \b is to make the character print to the same space
printf("\b%c", sequence[i]);
// now I want to delay here ~0.25s
}
}
}
所以我从 <time.h> 找到了一种让它休息那么长时间的方法.文档并制作了这个程序:
So I found a way to make it rest for that long from <time.h> documentation and made this program:
#include <stdio.h>
#include <time.h>
void sleep(double seconds) {
clock_t then;
then = clock();
while(((double)(clock() - then) / CLOCKS_PER_SEC) < seconds); //do nothing
}
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
sleep(0.25);
}
}
}
但是现在没有任何东西打印到控制台.有谁知道我如何才能产生我想要的行为?
But now nothing prints to the console. Does anyone know how I can go about producing the behavior I want?
编辑根据似乎流行的观点,我已将上面的代码更新为以下内容:
EDIT According to what appears to be popular opinion, I've updated my code above to be the following:
#include <stdio.h>
#include <unistd.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
/* fflush(stdout); */
// commented out to show same behavior as program above
usleep(250000); // 250000 microseconds = 0.25 seconds
}
}
}
推荐答案
写入控制台后需要刷新.否则,程序将缓冲您的输出:
You will need to flush after you wrote to the console. Otherwise, the program will buffer your output:
fflush(stdout);
这篇关于C sleep 方法阻止输出到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!