[Techtalk] getting the time as a string in c
Almut Behrens
almut-behrens at gmx.net
Thu Sep 29 07:05:05 EST 2005
On Wed, Sep 28, 2005 at 09:07:47PM +0100, Dan wrote:
> So what you want to do is:
>
> time_t timeInSeconds;
> const struct tm *timeptr;
>
> timeInSeconds = time(NULL);
> timeptr = localtime(&timeInSeconds); /* "&" means "pointer to" */
>
> /* Note: a second call to localtime()
> * might overwrite timeptr's memory.
> * that's not a concern here, though. */
> strftime(timestring, timestrsize, timeformat, timeptr);
>
> printf("%s\n", timestring);
In case the timeformat you want is just "%c", you can also use ctime()
(as Dan has mentioned in his other reply), which is somewhat shorter,
as ctime() directly returns the desired string (i.e. a pointer to a
char buffer, which you don't even need to allocate yourself).
A fully working program to print the current time would be no longer
than this
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
printf("%s", ctime(&t));
return 0;
}
compared to using strftime():
#include <stdio.h>
#include <time.h>
#define TSTR_MAXSIZE 40
int main(void) {
char timestring[TSTR_MAXSIZE];
time_t t = time(NULL);
const struct tm *timeptr = localtime(&t);
strftime(timestring, TSTR_MAXSIZE, "%c", timeptr);
printf("%s\n", timestring);
return 0;
}
Cheers,
Almut
P.S.: according to my experiences from giving introductory courses,
most problems learners of C are facing revolve around memory and
pointers:
* where is data stored
* who is resposible for the associated memory/buffers, i.e.
* who allocates it
* who needs to free it (if it's dynamic)
* how to address it, i.e. when to use *foo, foo or &foo
So, if you don't want your program to segfault, it's essential to get a
good grasp if this stuff... ;)
More information about the Techtalk
mailing list