Hello,
I have developed a sample program that should get the difference between a start time and an end time. I then use the seconds to calculate how many days has elapsed between those 2 times.
This is for a logging application that after a user specified number of days. The logs will be rolled over and a new start time will be set. The user can decide how many days the log will be replaced.
I added a small sleep to get the general idea, but normally this will be logging for days.
Is this the best and most portable (linux/windows) way to do this? Any potential pitfalls in this design?
Many thanks for any suggestions,
Code:
#include <time.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
time_t start_timestamp;
time_t end_timestamp;
struct tm time_days;
double seconds = 0;
size_t cumulative_days = 0;
#define FORMAT_TIME_SIZE 64
char format_time[FORMAT_TIME_SIZE];
#define DAY 3600 /* Seconds in one day */
#define MAX_DAYS 10 /* Roll over log after 10 days */
/* Current time of starting application */
time(&start_timestamp);
time_days = *localtime(&start_timestamp);
/* Print the current time at the start */
memset(format_time, 0, sizeof format_time);
strftime(format_time, sizeof format_time, "%c", &time_days);
printf("timestamp start [ %s ]\n", format_time);
/* Simulate a simple sleep. This could be logging for many days */
sleep(10);
/* Current time after delay print the results */
time(&end_timestamp);
time_days = *localtime(&end_timestamp);
memset(format_time, 0, sizeof format_time);
strftime(format_time, sizeof format_time, "%c", &time_days);
printf("timestamp end [ %s ]\n", format_time);
/* Get the current difference in seconds */
seconds = difftime(end_timestamp, start_timestamp);
printf("Seconds elapsed [ %f ]\n", seconds);
/* Calculate how many days have elapsed */
cumulative_days = DAY * seconds;
/* What are we going to do */
if(cumulative_days <= MAX_DAYS) {
printf("Delete log and start over\n");
}
else {
printf("Not there yet, keep appending the current log\n");
}
return 0;
}