MagicGroose
MagicGroose

Reputation: 83

How do you implement ctime in C to store into a character buffer?

If you use printf such as:

printf("Time as a basic string = %s", ctime(&seconds));

The output would be:

Wed, 28 Oct 2009 11:35:37

How do I store this output that ctime generates so that:

char result[80] = ctime(&seconds);

Whatever I try just doesn't seem to work.

Upvotes: 0

Views: 1229

Answers (3)

abhiarora
abhiarora

Reputation: 10430

You can use this function int snprintf(char *str, size_t size, const char *format,...);.

By it, you can format your string. For example,

snprintf(result, MAX, "Time as a basic string = %s", ctime(&seconds));

and it will copy the string "Time as a basic string = Wed, 28 Oct 2009 11:35:37" into the result character array. You can add any string along with string returned by ctime(&seconds) using snprintf().

Someone has mentioned an alternate way of copying a string. For that, you need to declare result as a pointer to character and use strdup(). You can also use it but i wouldn't prefer it if your code is being written for Embedded Device due to dynamic memory allocation.

Upvotes: 0

Tommy
Tommy

Reputation: 100622

strcpy as already proposed by multiple comments (hence this being a community wiki — it's not truthfully my answer) is correct for the use case given; also consider switching your array result to a pointer and using strdup to avoid having to make an assumption about string length at the cost of being responsible for a later free. So:

char result[80]; 
strcpy(result, ctime(&seconds));

Or:

char *result = strdup(ctime(&seconds));

... when you're done using result: ...
free(result);

Upvotes: 1

jxh
jxh

Reputation: 70402

You want to use ctime_r instead of ctime.

char result[80];
ctime_r(&seconds, result);

Upvotes: 2

Related Questions