简体   繁体   中英

Calling time in C++ changes my struct tm

I am trying to compare the current time to the date modified time of a file and am experiencing a strange issue. I have a struct tm * which holds the time the file was modified, but this is changed to the current date after I call time(NULL).

My code:

  printf("month: %d\n", tmst->tm_mon);
  time_t curTime = time(NULL);
  printf("month: %d\n", tmst->tm_mon);
  struct tm * curSt = localtime ( &curTime );
  printf("month: %d\n", tmst->tm_mon);

..where st is a struct stat for the file. Output is:

month: 11
month: 5

Why is this? What should I be doing differently?

From the documentation:

The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime.

Read documentation.

Documentation tells you how functions work.

(That localtime returns a pointer is a big clue: who do you think frees the pointee? :D)

As documented in the localtime(3) manual page:

The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.

You need to copy the value out if you don't want it to be modified out from under you, eg:

// Dereference and copy the result:
struct tm tmst = *localtime ( &st.st_mtime );

You can also use the reentrant variant localtime_r to copy the result into a parameter passed into it, but note that this function is not portable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM