gpt4 book ai didi

在 C 中创建延迟

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:55 24 4
gpt4 key购买 nike

我是编程新手。我一直在试图找出一个时间延迟来减慢我的程序的执行速度。我一直在做研究,但找不到有效的方法 我读过关于 nanosleepsleep 我都试过了,但是当我把它们放在 for 循环,它会等待几秒钟,然后执行整个 for 循环,而不会在迭代之间暂停。也许我的代码有错误?我已将其包含在下面。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
FILE *fp;
int i;

/* open the file */
fp = fopen("/dev/pi-blaster", "w");
if (fp == NULL) {
printf("I couldn't open pi-blaster for writing.\n");
exit(0);
}

/* write to the file */
for(i=99;i>=0;i--){
sleep(1);
fprintf(fp, "0=0.%d\n",i);
}
/* close the file */
fclose(fp);

return 0;
}

最佳答案

正在缓冲写入您的文件 fpfflush(fp) 在 for 循环内,以便它在下一次迭代之前将数据写出到文件中。否则,它将向缓冲区写入一行,休眠一秒钟,写入缓冲区,休眠一秒钟,等等,然后在缓冲区填满或 fclose(fp) 时将缓冲区刷新到文件 被调用。 man fflush 获取更多详细信息。

关于在 C 中创建延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15049720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com