View Single Post

   
  #10 (permalink)  
Old 06-23-2008, 11:46 AM
Gary R. Schmidt
 
Posts: n/a
Default Re: Solaris 10: How can I get a date that is exactly 30 days back?

More fixes in-line.

Chris Ridd wrote:
> On 2008-06-20 00:59:15 +0100, Anoop <anoopkumarv@gmail.com> said:
>
>> On Jun 19, 3:31 pm, Chris Ridd <chrisr...@mac.com> wrote:
>>> On 2008-06-19 19:51:25 +0100, Anoop <anoopkum...@gmail.com> said:
>>>
>>>> OK - at the risk of being flamed as off-topic, can someone please help
>>>> me with a perl command that gives me the date that is 30 days back?
>>>
>>> perl -e 'print scalar(localtime(time-30*24*60*60)),"\n"'
>>>
>>> Cheers,
>>>
>>> Chris

>>
>> Thanks a lot for the help.
>>
>> I finally ended up using a c program that someone had written [Link:
>> http://groups.google.com/group/comp....f0c8348ef3ef1d
>> ]
>>
>> I created the file dateback.c with the content:

>
> You do have a couple of buffer overflows in this code. Fixes are inline
> below:
>
>>
>> #include <time.h>
>> #include <stdio.h>

#include <stdlib.h>
>>
>> #define ONEDAY (60*60*24)
>> #define DEFAULT_FORMAT "%d-%b-%Y"
>>
>> int main(int argc,char *argv[])
>> {
>> time_t now;
>> char *date_format=NULL;
>> struct tm *now_s;
>> int daysback;
>> char stamp[80];
>>
>> if (argc < 2 || argc > 3)
>> {
>> fprintf(stderr,"usage: daysback <number of days>
>> [\"<date format>\"]\n");
>> exit(2);
>> }
>>
>> daysback=atoi(argv[1]);
>>
>> if (argc==3)
>> {
>> date_format=(char *)malloc(strlen(argv[2]));

>
> date_format=(char *)malloc(strlen(argv[2])+1);

date_format = malloc(strlen(argv[2])+1);
>
>> strcpy(date_format,argv[2]);
>> }
>> else if (getenv("DAYSBACK"))
>> date_format=(char *)getenv("DAYSBACK");
>>
>> if ((!date_format) || (*date_format=='\0'))
>> {
>> date_format=(char *)malloc(strlen(DEFAULT_FORMAT));

>
> date_format=(char *)malloc(strlen(DEFAULT_FORMAT)+1);

date_format = malloc(strlen(DEFAULT_FORMAT)+1);
>
>> strcpy(date_format,DEFAULT_FORMAT);
>> }
>>
>> now=time(0)-daysback*ONEDAY;
>> now_s=localtime(&now);
>>
>> strftime(stamp,80,date_format,now_s);
>> puts(stamp);
>>
>> return(0);
>>
>> }

>
> You're leaking the things you're mallocing too, but that doesn't matter
> in something this small.
>

Don't cast the return values of malloc/calloc/realloc in C code. Ever.

Cheers,
Gary B-)
Reply With Quote