Idea on how to create a C function that takes a character string and returns a character string with date and time -


i'm pretty new c , write function takes character string , returns character string current date , time in front. need logging function don't want print directly output stream.

#define time_format "[%y-%m-%d %h:%m:%s] "  char *logmsg(char *msg) {   char timestr[23];   time_t tms;   struct tm *localtime;    tms = time(null);   localtime = localtime(&tms);   strftime(timestr, sizeof(timestr), time_format, localtime);    int lenmsg = strlen(msg);   int newlen = sizeof(timestr) + lenmsg + 1;    char *newstr;    newstr = (char *) calloc(newlen,sizeof(char));   strcat(newstr,timestr);   strcat(newstr,msg);   return newstr; } 

i know bad idea allocate new memory every time call function functionality want. don't want limit message predefined length.

just idea or design pattern helpful. lot!

the right answer depends on intend function. can presume, using function create log string, use several times in program. going approach have currently, code littered confusing calls free() after each call logmsg. having caller allocate memory litter code calloc , free.

i recommend have caller worry memory allocation, way c (see strftime() used). though mentioned don't want limit length of message, recommend allocating once sufficiently large limit , free once @ end, in calling program. avoid many calls calloc , free.

hope helps.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -