c++cdatesystemruntime-error

How to get yesterday's date from system date and append to string?


I am a beginner in C programming and trying to get the yesterday’s date through c code using system date and append in the string "yesterdayDate_dt" like this yesterdayDate_dtmmddyy but facing run time error “bus error 10” .

My code as below  

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
 
int main(void)
{
   time_t now = time(NULL);
   struct tm *t = localtime(&now);
 
  int dInt = t->tm_mday+1;
  int mInt = t->tm_mon -1;
  int yInt = t->tm_year+1900;
  char *date= "23";
  char *month = "01";
  char *year = "13";
 
  sprintf(date, "%d", dInt);
  sprintf(month, "%d", mInt);
 
   char *yestDt = (char *)malloc(strlen(date)+strlen(month)+strlen(year)+1);
   strcpy(str,month);
   strcat(str,date);
   strcat(str,year);
   printf("str:%s",yestDt);
   return 0;
}

Solution

  • Please look into sprintf documentation and try the below code

    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>
    #include <string.h>
     
    int main(void)
    {
        char yestDt[23];
        time_t now = time(NULL);
        now = now - (24*60*60);
        struct tm *t = localtime(&now);
        sprintf(yestDt,"yesterdayDate_dt%02d%02d%02d", t->tm_mon+1, t->tm_mday, t->tm_year - 100);
        printf("Target String: \"%s\"", yestDt);
        return 0;
    }