Originally Posted by
Dave_Sinkula
I should better read more on standard function in C. This is the 2nd time that Dave have pointed me to an existing function in C. And as always using strftime() did help alot.
Anyway I did found out what is cause the problem that I mention in my first post ( actually someone pointed to me the problem ).
In the getProcessDate function, the array declaration is wrong. I failed to include space for the null terminator in array declaration.
Changing the declaration from
Code:
char year[4];
char day[2];
char month[2];
To this
Code:
char year[5];
char day[3];
char month[3];
Solve the problem in running the program in Release mode.
Although I'm curious to why this kind of error is not present in Debug mode.
here are the changes in the code that I've made and also with the strftime() solution.
Code:
#include <string.h>
#include <stdio.h>
#include <time.h>
#define HOUR 261
#define MINUTE 262
#define DAY 263
#define MONTH 264
#define YEAR 265
void padUpString(char *str, char* filler, int len, int fillAtTheEnd)
{
int i;
char newstr[50]="";
int strLen = strlen(str);
int diff = len - strLen;
if (strLen < len)
{
for (i=0; i< len ; i++)
{
if (fillAtTheEnd)
{
if( i >= strLen) *(str+strLen++)=*filler;
}else
{
if( i < diff) strcat(newstr,filler);
}
}
if (!fillAtTheEnd)
{
strcat(newstr,str);
strcpy(str,newstr);
}
}
}
int getCurrentTimeValue(int timeElement)
{
struct tm *tm_today;
time_t t;
t = time(NULL);
tm_today = localtime(&t);
if (timeElement == HOUR)
{
return tm_today->tm_hour;
}
if (timeElement == MINUTE)
{
return tm_today->tm_min;
}
if (timeElement == DAY)
{
return tm_today->tm_mday;
}
if (timeElement == MONTH)
{
return tm_today->tm_mon + 1;
}
if (timeElement == YEAR)
{
return tm_today->tm_year + 1900;
}
return -1;
}
void getProcessDate(char *procDate)
{
//YYYY-MM-DD
char currentTime[11];
char year[5];
char day[3];
char month[3];
sprintf(year,"%d",getCurrentTimeValue(YEAR));
sprintf(month,"%d",getCurrentTimeValue(MONTH));
sprintf(day,"%d",getCurrentTimeValue(DAY));
padUpString(month,"0",2,0);
padUpString(day,"0",2,0);
sprintf(currentTime,"%s-%s-%s",year,month,day);
currentTime[10] = '\0';
memcpy(procDate,currentTime,sizeof(currentTime));
}
void getProcessDateTwo(char *procDate){
//YYYYMMDD
char currentTime[11];
time_t tval;
struct tm *tmptr;
tval = time(NULL);
tmptr = localtime(&tval);
strftime(currentTime,sizeof(currentTime),"%Y-%m-%d",tmptr);
currentTime[10] = '\0';
memcpy(procDate,currentTime,sizeof(currentTime));
//return currentTime;
}
int main()
{
char date[30];
char dateTwo[30];
getProcessDate(date);
getProcessDateTwo(dateTwo);
printf("getProcessDate %s\n",date);
printf("getProcessDateTwo %s \n",dateTwo);
return 0;
}
OutPut
getProcessDate 2006-05-24
getProcessDateTwo 2006-05-24
the getProcessDateTwo function uses the strftime(). Same result when running in Release and Debug mode.
regards,
jaro