cLearner130124
cLearner130124

Reputation: 13

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;
}

Upvotes: 1

Views: 4820

Answers (3)

Laszlo Lebrun
Laszlo Lebrun

Reputation: 1

I prefer not to fiddle with now and use clones of tm* and time_t.

//***Variables for Time***
tm* timeinfo;  
tm* yesterdaytimeinfo;  
time_t now;
time_t yesterdaynow;
static char charbuff[120];  //Char buffer for many functions
 
 
//*** In program ***
yesterdaynow = now - 86400;
yesterdaytimeinfo = localtime(&yesterdaynow);
strftime(charbuff, 30, "%x ", yesterdaytimeinfo);
println();
print(charbuff);

Upvotes: 0

Drew Dormann
Drew Dormann

Reputation: 63912

This code is not legal:

sprintf(date, "%d", dInt);

sprintf expects the first parameter to point to writable character storage. date is not pointing to writable storage.

Try changing the declaration of date to a writable array of characters:

char date[3];

Upvotes: 0

User97693321
User97693321

Reputation: 3346

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;
}

Upvotes: 4

Related Questions