C programming

1 0 0
                                    

IF someone interested in and don't understands how it work's... Nothink difficult, the time is given in seconds from midnight, so for the seconds i have to do rest of this number, than divide it per 60 and do rest of this for the minutes than another time divide it per 60 and apply a rest of 24, than the time i need is one hour later than i obtain so i add 1 to hours, in main function i have a loop that controls many times per second the time and when the second changes it rewrite a time on the same line.

#include <stdio.h>

#include <time.h>

#include <string.h>

#include <stdlib.h>

/* FUNCTION THAT RETURNS A STRING CONTAINING A TIME */

char *getTimeString(int t, char *time_str) {

char temp;

short int t_sec, t_min, t_hours;

char t_string_h[2], t_string_m[2], t_string_s[2];

t_sec = t%60;

itoa(t_sec, t_string_s, 10);

if(t_sec<10) { //IN CASE MY NUMBER IS LASS THAN 10 I'M ADDING A ZERO IN FRONT OF THIS NUMBER

strcat(t_string_s, "0");

temp = t_string_s[0];

t_string_s[0] = t_string_s[1];

t_string_s[1] = temp;

}

t_min = t/60%60;

itoa(t_min, t_string_m, 10);

if(t_min<10) {

strcat(t_string_m, "0");

temp = t_string_m[0];

t_string_m[0] = t_string_m[1];

t_string_m[1] = temp;

}

t_hours = t/60/60%24+1;

itoa(t_hours, t_string_h, 10);

if(t_hours<10) {

strcat(t_string_h, "0");

temp = t_string_h[0];

t_string_h[0] = t_string_h[1];

t_string_h[1] = temp;

}

/* CANCATENATES TIME */

time_str = strcat(t_string_h, ":");

time_str = strcat(time_str, t_string_m);

time_str = strcat(time_str, ":");

time_str = strcat(time_str, t_string_s);

return time_str;

}

/* MAIN FUNCTION */

int main() {

int i;

char *t_now;

char *t_prec = malloc(sizeof(char)*15);

t_prec = getTimeString(time(NULL), t_prec);

printf("\t\t\t\t %s", t_prec);

/* MAIN LOOP THAT CONTROLS THE TIME AND REPRINT IT */

for(i=0; ;i++) {

t_now = getTimeString(time(NULL), t_now);

if(strcmp(t_now, t_prec) != 0)

printf("\r\t\t\t\t %s ", t_now);

t_prec = t_now;

}

}

This is it.

You've reached the end of published parts.

⏰ Last updated: Dec 14, 2018 ⏰

Add this story to your Library to get notified about new parts!

A simple timer with CWhere stories live. Discover now