portable way to deal with 64/32 bit time_t

两盒软妹~` 提交于 2019-12-17 16:32:54

问题


I have some code which is built both on Windows and Linux. Linux at this point is always 32bit but Windows is 32 and 64bit. Windows wants to have time_t be 64 bit and Linux still has it as 32 bit. I'm fine with that, except in some places time_t values are converted to strings. So when time_T is 32 bit it should be done with %d and when it is 64bit with %lld... what is the smart way to do this? Also: any ideas how I may find all places where time_t's are passed to printf-style functions to address this issue?

edit: I came up with declaring TT_FMT as "%d" or "%lld" and then changing my printfs as in printf("time: %d, register: blah") to be printf("time: " TT_FMT ", register: blah") Is there a better way? And how do I find them all?


回答1:


According to the C standard, time_t is an arithmetic type, "capable of representing times". So, it could be double for example. (Posix mentions this more explicitly, and also guarantees that time() returns the number of seconds since the Epoch—the latter is not guaranteed by the C standard.)

Maybe the cleanest solution is to convert the value to whatever type you want. You may want one of unsigned long long or unsigned long:

printf("%llu\n", (unsigned long long)t);



回答2:


I think the only truly portable way is to use strftime to convert the time_t to a string.

If you're sure that you're only operating on platforms where time_t is an int, you could cast to intmax_t (from stdint.h) and print it using PRIdMAX (from inttypes.h).




回答3:


If you want to go with the macro specifier, I would recommend one minor tweak. Instead of encapsulating the entire specifier, encapsulate just the modifier:

#ifdef 64_BIT_TIME
  #define TT_MOD "ll"
#else
  #define TT_MOD ""
#endif

and then using it like this:

printf("current time in seconds is: %" TT_MOD "u", time(0));

The reason why is that while you primarily want the second in decimal, every so often you may want hex (or perhaps you want leading 0's). By only having the modifier there, you can easily write:

"%" TT_MOD "x"   // in hex
"%08" TT_MOD "d"  // left pad with 0's so the number is at least 8 digits



回答4:


Slight adjustment on Alok's answer, it's signed on both Windows and Linux, so:

printf("%lld\n", t);

is cleaner.



来源:https://stackoverflow.com/questions/2467418/portable-way-to-deal-with-64-32-bit-time-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!