How do I make my program iterate only once every given time (ex 1/s)?

Viewed 33

Let's say that for example I have a for loop which is reading instructions line by line from a .txt file and what I wish to do is make the program execute those instructions once every second or so. How can I possibly do this?

Here's the code for my loop:

  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");
    }
  }

Please ignore the variable names, it's just for examplifying.

1 Answers

make the program execute those instructions once every second or so

Make it wait until the required time passed.

Assuming you want to have the program wait for one or more seconds (and you are on a POSIX system, like Linux, which brings sleep()) you can do this like so:

#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. */
    }
  }
Related