/* * progrsm to demonstrate how to get time * get time first, wait 10 seconds, then get time, compare to first * demonstrates how the *time() functions use static storage and * return pointers * * Matt Bishop, ECS 36A, Fall Quarter 2019 */ #include #include #include /* * print the given time structure */ void prboard(struct tm *tock) { printf("In detail . . .\n"); printf("\tYear: %d\n", tock->tm_year + 1900); printf("\tMonth: %d\n", tock->tm_mon + 1); printf("\tDay: %d\n", tock->tm_mday); printf("\tDay of week: %d\n", tock->tm_wday); printf("\tDay of year: %d\n", tock->tm_yday); printf("\tHour: %d\n", tock->tm_hour); printf("\tMinute: %d\n", tock->tm_min); printf("\tSecond: %d\n", tock->tm_sec); printf("\t%s daylight savings time\n", tock->tm_isdst ? "On" : "Off"); printf("---------------------------\n"); } /* * get the current time, then print it */ time_t getime(void) { time_t tick; /* current time since the epoch */ /* * get the current time */ if ((tick = time(NULL)) == -1){ perror("time"); return(1); } /* * now print it; note it has a trailing newline */ printf("%s", ctime(&tick)); /* return the time */ return(tick); } /* * the main routine */ int main(int argc, char *argv[]) { struct tm *tod1; /* current time as structure */ struct tm *tod2; /* time 10 seconds later as structure */ time_t tick, newtick; /* * get program start time */ printf("The initial time ...\n"); if ((tick = getime()) == -1) return(1); tod1 = localtime(&tick); prboard(tod1); /* * make sure you get a different time */ printf("Now a 10-second pause ...\n"); (void) sleep(10); /* * noiw get the later time */ printf("Now the new time ...\n"); if ((newtick = getime()) == -1) return(1); tod2 = localtime(&newtick); prboard(tod2); /* * now compare the new time with the old one * they should be different but are not! */ printf("Now we check the original time\n"); prboard(tod1); printf("Here's why:\n"); printf(" * pointer to original time: %p\n", (void *) tod1); printf(" * pointer to new time: %p\n", (void *) tod2); /* * bye! */ return(0); }