2

I'm relatively new to programming and C, but I've been trying to create my own "delay" function in C. In essence, it would pause the program for the number of seconds the user puts in. For example:

    int main (int argc, char *argv[]) {
      printf("There will now be a ten second pause.\n");
      delay(10);
      printf("Ten seconds have now passed.\n");
      return 0;
    }

The program would print the first output, wait ten seconds, then print the last one. My current function looks like this:

    void delay(unsigned int seconds) {
      time_t old_time = time(NULL), target_time = old_time;
      while((target_time - old_time) < seconds) target_time = time(NULL);
    }

The function is decently accurate with waiting the specified amount of time given. However, the the program does not print the first output before delaying, which is certainly not what I want :( The program instead waits ten seconds as soon as the program starts, and then prints the two statements, instead of printing the first statement, delaying, then printing the last.

Am I missing something with my understanding of time()? Or will this not work for some reason? Again, for clarification, I'm trying to fix the problem where the delay happens BEFORE anything else in the program happens, even if the function comes after other functions. Any thoughts or suggestions for helping me understand this would be awesome!

Thanks! :)

Bradass
  • 89
  • 7

1 Answers1

1

It's likely your problem is because the stdout stream is buffered. Check out this link, it has a good writeup on the subject.

Also, is there a reason you're not using the C standard library's sleep() function?

Community
  • 1
  • 1
Mike Schiffman
  • 240
  • 3
  • 9
  • 1
    Thanks on the link, very informative! And you are correct about the stream being buffered. I looked up sleep() and tried using it, but the program didn't recognize it. I included both: #include and #include "windows.h" and it still didn't work, so I thought it would be fun to create my own – Bradass Sep 09 '14 at 22:53