transiti0nary transiti0nary - 24 days ago 14
C Question

Converting a time_t to a string in a given format in C

So as part of an assignment we've been given this skeleton function to complete:

char *time2str(time_t time) {
static char *str_fmt = "%02d/%02d/%4d %02d:%02d";
char *time_s = ""; // appropriate string allocation here

return time_s;
}


However I'm very new to C and struggling to get my head around what I'm doing wrong (and also how pointers work)... I've been trying to use
localtime
to get a
struct
with which I can access the specific values I need to add to the string in the given format. Something like this:

char *time2str(time_t time) {
static char *str_fmt = "%02d/%02d/%4d %02d:%02d";

struct tm *info;
info = localtime(&time);

char *time_s = (str_fmt, info->tm_mday, info->tm_mon...etc...);

return time_s;
}


However I'm just getting warnings and errors at compile no matter what I try and do (remove
str_fmt
and just put the format in quotations at the beginning of
time_s
, using
info.tm_mday
etc rather than
info->tm_mday
). However nothing seems to have any effect and I can't find anything online that helps me solve the problem in the way we have been asked.

Can anyone help? It's probably worth mentioning that we are doing this on MINIX 3.2.1 using MINIX system calls.

Answer

Using what you've given us, I assume the function should be:

char *time2str(time_t time) {
    static char *str_fmt = "%02d/%02d/%4d %02d:%02d";

    // Convert to struct tm
    // localtime returns a pointer, so shallow copy to info
    struct tm info = *localtime(&time);

    // Allocate memory for ##/##/#### ##:##
    char *time_s = malloc(17);  // Space for 16 chars and eos
    if (NULL == time_s) {// Handle error.....}
    sprintf(time_s, str_fmt, info.tm_mon + 1, info.tm_mday, 1900 + info.tm_year,
           info.tm_hour, info.tm_min);

    return time_s;
}
Comments