Mike
Mike

Reputation: 11

How do I update a time displayed in C?

I'm trying to display the time, then wait for a period of time, then display the updated time. My code however prints the same time, without updating it.

this is my code so far:

#include<stdlib.h>
#include<time.h>
#include<sys/time.h>

int main(){
time_t timer;
time(&timer);
struct tm* time;
time = localtime(&timer);

printf("%s", asctime(time));
fflush(stdout);

sleep(4); //my attempt at adjusting the time by 4 seconds

time = localtime(&timer); // "refreshing" the time?
printf("%s", asctime(time));

return(0);

}

and my output is:

ubuntu@ubuntu:~/Desktop$ ./tester
Sat Feb 25 08:09:01 2012
Sat Feb 25 08:09:01 2012

ideally, i'd be using ctime(&timer) instead of localtime(&timer), but I'm just trying to adjust the time by 4 seconds for now. Any help would be appreciated.

Upvotes: 1

Views: 3305

Answers (2)

Pintu Patel
Pintu Patel

Reputation: 163

#include<stdlib.h>
#include<time.h>
#include<sys/time.h>
#include <stdio.h>

int main(){
                time_t timer;
                time(&timer);
                struct tm* time_real;//time is function you can't use as variable
                time_real = localtime(&timer);
                printf("%s", asctime(time_real));
                sleep(4);
                time(&timer);//update to new time
                time_real = localtime(&timer); // convert seconds to time structure tm
                printf("%s", asctime(time_real));

return(0);
}

Upvotes: 0

Mat
Mat

Reputation: 206929

localtime just converts a (pointer to) struct timep to a struct tm, it doesn't check what time it is at all.

Just call time(&timer) after the sleep if you want the new current time, and don't give a local variable the same name as a library function you're using in that same block.

(And you're missing two headers - <stdio.h> for printf, and <unistd.h> for sleep - make sure you enable warnings on your compiler.)

Upvotes: 4

Related Questions