Tick-Tock Goes the Clock, Part I

The other day I had this strong urge to write myself a text mode clock program, one that runs at the command prompt. This desire harkens back to my days programming text mode computers: I don’t need a clock, I just wanted to see if I could code one.

The clock must display the current time of day, which can easily be obtained from the ctime() function, defined in the time.h header. This function requires an argument representing a time_t value, the number of seconds ticked since the dawn of the Unix epoch, January 1, 1970:

time(&now);

Variable now is a time_t type. Its address is passed to the time() function, which sets the value of variable now to the current epoch value. The now variable can then be used in the ctime() function to return a time string, but for my clock I just want the current hours and minutes. So instead of ctime(), I use the localtime() function, which fills a tm structure with individual time tidbits. Two members of the structure are tm_hour and tm_minute, which is what I want.

Whew!

Full details of all this timely nonsense can be found in my books, which I urge you to read.

Below is the source code required to read the system’s time, extract the current hour and minute, and then display those values.

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

int main()
{
    time_t now;
    struct tm *clock;

    /* fetch the current time */
    time(&now);
    /* fill the time structure */
    clock = localtime(&now);
    /* display the clock */
    printf("It is now %2d:%02d\n",
            clock->tm_hour,
            clock->tm_min
          );

    return(0);
}

And here’s the output:

It is now 11:41

Yes, the clock program works, but I want more! I want the output to update every minute. Like a digital clock, I want my program to output 11:42 to reflect the current time — and then 11:43 and so on. To accomplish this task requires additional programming, which I cover in next week’s Lesson.

Leave a Reply