In C, I'm trying to portably implement gmtime_r (I'm aware of the gmtime_r 
macro and comments in time.h) using gmtime_s and this snippet appears to work 
fine. What's a cleaner or more robust solution?


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

#if defined(__MINGW64_VERSION_MAJOR)
/* XXX why isn't this in sec_api/time_s.h? */
# if defined(_USE_32BIT_TIME_T)
#  define gmtime_s _gmtime32_s
# else
#  define gmtime_s _gmtime64_s
# endif
#elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
# define BUILDING_WITH_MINGW32
# define gmtime_r(tp, tm) (gmtime((tp)))
# define localtime_r(tp, tm) (localtime((tp)))
#endif

#if defined(_MSC_VER) || defined(__MINGW64_VERSION_MAJOR)
# define gmtime_r(tp, tm) ((gmtime_s((tm), (tp)) == 0) ? (tm) : NULL)
# define localtime_r(tp, tm) ((localtime_s((tm), (tp)) == 0) ? (tm) : NULL)
#endif


int
main(int argc, char *argv[])
{
  time_t rawtime;
  struct tm utc_tm, local_tm, tmp_tm, *my_utc_tm, *my_local_tm;
  char buffer[1024] = "";

  time(&rawtime);
  my_utc_tm = gmtime_r(&rawtime, &utc_tm);

#ifdef BUILDING_WITH_MINGW32
  /* save the *utc_tm so it doesn't get clobbered */
  memcpy(&tmp_tm, my_utc_tm, sizeof(struct tm));
  my_utc_tm = &tmp_tm;
#endif

  my_local_tm = localtime_r(&rawtime, &local_tm);


  if (strftime(buffer, sizeof(buffer),
               "UTC: %A, %B %d, %Y %H:%M", my_utc_tm))
    puts(buffer);

  if (strftime(buffer, sizeof(buffer),
               "Local: %A, %B %d, %Y %H:%M %z", my_local_tm))
    puts(buffer);

  return 0;
}



Jon

---
Fail fast. Fail often. Fail publicly. Learn. Adapt. Repeat.
http://thecodeshop.github.com | http://jonforums.github.com/
twitter: @jonforums

------------------------------------------------------------------------------
Live Security Virtual Conference
Exclusive live event will cover all the ways today's security and 
threat landscape has changed and how IT managers can respond. Discussions 
will include endpoint security, mobile security and the latest in malware 
threats. http://www.accelacomm.com/jaw/sfrnl04242012/114/50122263/
_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to