The problem is that localtime returns a pointer to static data. This means that if you call it a second time, the contents will just be overwritten, and the first pointer will point to the new value, just as the second pointer does.
What you need to do is make a copy of the struct tm on each call. I would do something like this:
Code:
#include <stdio.h>
#include <time.h>
struct tm *get_time_stamp(struct tm *t){
time_t timer = time(NULL);
struct tm *l;
l = localtime(&timer);
if (!l)
return NULL;
*t = *l;
return t;
}
int main(void)
{
struct tm start_time;
struct tm end_time;
long i;
get_time_stamp(&start_time);
/* do something for a while */
for (i = 0; i < 1000000000L; i++)
;
get_time_stamp(&end_time);
printf("Start: %02d:%02d:%02d\n", start_time.tm_hour, start_time.tm_min, start_time.tm_sec);
printf(" End: %02d:%02d:%02d\n", end_time.tm_hour, end_time.tm_min, end_time.tm_sec);
return 0;
}
My output:
Code:
Start: 12:34:28
End: 12:34:30
You can check the return of get_time_stamp for NULL in case of error.
And to your second question:
printf("%20s", the_string); or printf("%-20s", the_string);