3

I'm having problems converting from unix epoch time to a character array. I know how to do it and the conversion is happening correctly but after I make a call to gmtime() or localtime(), all input gets random characters appended to to. I have pinned the problem down and ONLY lines calling either localtime() or gmtime() cause this problem (seriously... I have them in and the problem occurs, I comment them out, remake, and the problem no longer occurs). Here is the function where the function is called:

void ls(){

int clusterSize = bootRecord[0];
int root = bootRecord[2];

for (int i = 0; i < bootRecord[0] / 128 ; ++i){
    fseek(fp, clusterSize * root + 128 * i, SEEK_SET);
    if(directoryTable[i].name[0] != 0x00){

        time_t rawtime = (time_t)directoryTable[i].creation;
        struct tm * curDate;

        curDate = localtime(&rawtime);

        printf("%s     %d      %s", directoryTable[i].name, directoryTable[i].size,
                        asctime(gmtime(&rawtime)));

    }
}
}

Right now I have the asctime(gmtime(&rawtime)) but I have tried separating them into several different statements but to no avail. Does anyone know of a useful alternative to localtime() or gmtime()? Or happen to know a solution to this particular problem? Thank you.

Tom
  • 155
  • 1
  • 10
  • 1
    Did you try using `gmtime_r()` and/or `localtime_r()`? These 2 functions operate on `struct tm` allocated by caller and thus are generally safer. – Pavel Zhuravlev Feb 16 '12 at 06:26

1 Answers1

0

Whatever your problem is, it's unrelated to the way you're using the time functions. The following program works fine:

#include <stdio.h>
#include <time.h>

int main (void) {
    time_t now = time(0);
    printf ("Local time is %s", asctime (localtime (&now)));
    printf ("  UTC time is %s", asctime (gmtime (&now)));
    return 0;
}

printing out:

Local time is Thu Feb 16 14:15:51 2012
  UTC time is Thu Feb 16 06:15:51 2012

as expected.

You need to more clearly state what all input gets random characters appended to to means. If you mean that lines you type in mysteriously seem to have characters added to them, that's almost certainly a different problem which just happens to be exacerbated by the function calls.

I'd be first looking for (as an example) buffers which may be overflowing or code logic which doesn't transfer null terminators.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • The problem could be related to the way that he is using time functions. The `localtime` and `gmtime` is sharing a statically allocated `tm` structure in memory. – daparic Sep 14 '22 at 23:06