简体   繁体   English

C ++中的调用时间更改了我的结构tm

[英]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). 我有一个结构tm *,它保存文件被修改的时间,但是在我调用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. ..where st是一个struct stat的文件。 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. 返回的值指向一个内部对象,该对象的有效性或值可以通过随后对gmtime或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) localtime返回指针是一个大提示:您认为谁释放了pointe?

As documented in the localtime(3) manual page: localtime(3)手册页中所述:

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. 您也可以使用可重入变量localtime_r将结果复制到传递给它的参数中,但是请注意,此函数不可移植。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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