Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sleep function in while statement

Tags:

c

I can't understand why this code does not print current time in every one second. What is the problem here ?

#include <stdio.h>
#include <unistd.h>
#include <time.h>


int main(int argc, const char * argv[])
{
    while (1) {
        sleep(1);
        time_t tm;
        struct tm *t_struct;
        tm = time(NULL);
        t_struct = localtime(&tm);

        printf("%.2d:%.2d:%.2d", t_struct->tm_hour, t_struct->tm_min, t_struct->tm_sec);
    }
    return 0;
}
like image 568
rogi Avatar asked Nov 22 '25 16:11

rogi


1 Answers

stdout may be line buffered, so you might need to either fflush it after outputting text, or print a newline to make changes visible.

like image 75
eq- Avatar answered Nov 25 '25 07:11

eq-