What is time_t ultimately a typedef to?

后端 未结 10 2165
陌清茗
陌清茗 2020-11-22 08:34

I searched my Linux box and saw this typedef:

typedef __time_t time_t;

But I could not find the __time_t definition.

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 09:02

    The answer is definitely implementation-specific. To find out definitively for your platform/compiler, just add this output somewhere in your code:

    printf ("sizeof time_t is: %d\n", sizeof(time_t));
    

    If the answer is 4 (32 bits) and your data is meant to go beyond 2038, then you have 25 years to migrate your code.

    Your data will be fine if you store your data as a string, even if it's something simple like:

    FILE *stream = [stream file pointer that you've opened correctly];
    fprintf (stream, "%d\n", (int)time_t);
    

    Then just read it back the same way (fread, fscanf, etc. into an int), and you have your epoch offset time. A similar workaround exists in .Net. I pass 64-bit epoch numbers between Win and Linux systems with no problem (over a communications channel). That brings up byte-ordering issues, but that's another subject.

    To answer paxdiablo's query, I'd say that it printed "19100" because the program was written this way (and I admit I did this myself in the '80's):

    time_t now;
    struct tm local_date_time;
    now = time(NULL);
    // convert, then copy internal object to our object
    memcpy (&local_date_time, localtime(&now), sizeof(local_date_time));
    printf ("Year is: 19%02d\n", local_date_time.tm_year);
    

    The printf statement prints the fixed string "Year is: 19" followed by a zero-padded string with the "years since 1900" (definition of tm->tm_year). In 2000, that value is 100, obviously. "%02d" pads with two zeros but does not truncate if longer than two digits.

    The correct way is (change to last line only):

    printf ("Year is: %d\n", local_date_time.tm_year + 1900);
    

    New question: What's the rationale for that thinking?

提交回复
热议问题