Yamaha32088
Yamaha32088

Reputation: 4163

Creating a Delay in C

I am new to programming. I have been trying to figure out a time delay to slow down the execution of my program. I have been doing research and can not find one that works I have read about nanosleep and sleep I have tried both but when I put them in the for loop it waits a few seconds and then executes the entire for loop without pausing between iterations. Maybe I have an error in my code? I have included it below.

#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;
   }

Upvotes: 0

Views: 586

Answers (1)

Ian McMahon
Ian McMahon

Reputation: 1700

Writes to your file fp are being buffered. fflush(fp) inside the for loop so it writes data out to the file before the next iteration. Otherwise, it'll write a line to the buffer, sleep a second, write to the buffer, sleep a second, etc, and then flush the buffer to the file either when the buffer fills up or when fclose(fp) is called. man fflush for more details.

Upvotes: 4

Related Questions