比如说,我有一个for循环,它从一个.txt文件中逐行读取指令,我想做的是让程序每隔一秒左右执行一次这些指令。我怎样才能做到这一点呢?
下面是我的循环的代码。
for(j = 0; j < PC; j++) {
txtfilepointer = fopen(listWithTxtFilesToRead[j].name, "r");
while (fscanf(txtfilepointer, "%c %s", &field1, field2) != EOF ) {
// here it should be executing the given instruction every second or so...
printf("whatever the instruction told me to do");
}
}
请忽略变量名,这只是为了简化。
让程序每隔一秒左右执行一次这些指令。
让它等到规定的时间过去。
假设你想让程序等待一秒或多秒(而且你是在POSIX系统上,比如Linux,它带来了 sleep()
)你可以这样做。
#include <time.h> /* for time() */
#include <unistd.h> /* for sleep() */
#define SECONDS_TO_WAIT (3)
...
{
time_t t = time(NULL);
/* Instructions to execute go here. */
while ((time(NULL) - t) < SECONDS_TO_WAIT)
{
sleep(1); /* Sleep (wait) for one second. */
}
}