Programming 97
A simple example will suffice for now. When dealing with many time functions,
these functions use a time struct called tm, which is defined in /usr/include/
time.h. The struct’s definition is as follows.
struct tm {
int tm_sec; / seconds /
int tm_min; / minutes /
int tm_hour; / hours /
int tm_mday; / day of the month /
int tm_mon; / month /
int tm_year; / year /
int tm_wday; / day of the week /
int tm_yday; / day in the year /
int tm_isdst; / daylight saving time /
};
After this struct is defined, struct tm becomes a usable variable type, which
can be used to declare variables and pointers with the data type of the tm struct.
The time_example.c program demonstrates this. When time.h is included,
the tm struct is defined, which is later used to declare the current_time and
time_ptr variables.
time_example.c
#include <stdio.h>
#include <time.h>
int main() {
long int seconds_since_epoch;
struct tm current_time, *time_ptr;
int hour, minute, second, day, month, year;
seconds_since_epoch = time(0); // Pass time a null pointer as argument.
printf("time() - seconds since epoch: %ld\n", seconds_since_epoch);
time_ptr = ¤t_time; // Set time_ptr to the address of
// the current_time struct.
localtime_r(&seconds_since_epoch, time_ptr);
// Three different ways to access struct elements:
hour = current_time.tm_hour; // Direct access
minute = time_ptr->tm_min; // Access via pointer
second = ((int ) time_ptr); // Hacky pointer access
printf("Current time is: %02d:%02d:%02d\n", hour, minute, second);
}
The time() function will return the number of seconds since January 1,
- Time on Unix systems is kept relative to this rather arbitrary point in
time, which is also known as the epoch. The localtime_r() function expects two
pointers as arguments: one to the number of seconds since epoch and the
other to a tm struct. The pointer time_ptr has already been set to the address