0

I need to create a struct where is set a date. I googled something and i found the tm structure from the library time.h, but I'm having some troubles; I need to print some dates on a log file, here an example:

typedef struct tm* tm_;

...

void NEW_Job()
{
    time_t t;
    tm_ secs;
    t=time(NULL);
    secs=localtime(&t);
    add_QUEUEnode(generate_job());
    fprintf(f, "\n%d:%d.%d : New job created.", secs->tm_hour, secs->tm_min, secs->tm_sec);
}

I really don't know where i'm wrong.

Thanks in advance for the help :)

Lamberto Basti
  • 478
  • 1
  • 6
  • 24
  • One of my answers covers the use of that struct http://stackoverflow.com/questions/16164442/convert-seconds-from-jan-1st-1970-to-date-using-c-language/16166125#16166125 – Dariusz May 06 '13 at 16:16
  • Your code looks OK to me. What it does wrong? – Fabio Ceconello May 06 '13 at 16:22
  • 1
    `typedef struct tm* tm_;` -- Hiding pointer types behind typedefs is generally a bad idea. Drop the typedef and just declare `struct tm *secs;` – Keith Thompson May 06 '13 at 17:29

2 Answers2

0

The exact error wasn't there, but in another line of the code, exactly here:

void PCunload(int b)
{
    time_t t;
    tm_ secs;
    int hh, mm, ss;
    hh=(time(NULL)-n[b].start_time)/3600;
    mm=((time(NULL)-n[b].start_time)%3600)/60;
    ss=((time(NULL)-n[b].start_time)%3600)%60;
    t=time(NULL);
    secs=localtime(&t);
    n[b].job.priority=-1;
    -->>fprintf(f, "\n%d:%d.%d : PC number %d unloaded; elapsed time: %d:%d.%d", secs->tm_hour, secs->tm_min, secs->tm_sec, hh, mm, ss);
} 

There I tried to do the conversion inside the printf functions, but something goes wrong... My apologies!

Lamberto Basti
  • 478
  • 1
  • 6
  • 24
  • 2
    You seem to be missing an argument that matches up with the `"PC number %d"` bit... – twalberg May 06 '13 at 16:39
  • 1
    Don't call `time(NULL)` multiple times. Just call it once and store the value in `t`, then use `t`. Apart from the inefficiency, you risk having the clock advance between calls to `time()`. – Keith Thompson May 06 '13 at 17:30
0

strftime() can help you printing date and time at your favorite format. Please take a look at man strftime.

rakib_
  • 136,911
  • 4
  • 20
  • 26