2

I'm attempting to create timestamps for my program. On my sister's Mac (using Xcode 4.2) this code works perfectly fine:

struct tm * timeInfo;
time_t rawtime;
time (&rawtime);
timeInfo = localtime (&rawtime);
string timestamp(asctime(timeInfo));

However, on my PC running Visual Studio 2012 I get errors for localtime and asctime that tell me they are unsafe functions and it recommends using localtime_s and asctime_s. However, the function parameters are different. I've tried researching the functions as best I can, but I can't get it to work.

Any help with getting that to work would be much appreciated.

edit:

struct tm * timeInfo;
time_t rawtime;
time (&rawtime);
timeInfo = localtime_s (&rawtime);
string timestamp(asctime_s(timeInfo));
4

1 回答 1

4

这些函数具有不同参数的原因是缺乏安全性是由只有一个参数引起的。特别是,asctime()使用单个缓冲区来返回时间。因此,如果您执行以下操作:

char *s1 = asctime((time_t)0);   // 1-Jan-1970 00:00:00 or something like that. 
time_t t = time();
char *s2 = asctime(t);
cout << "1970: " << s1 << " now:" << s2 << endl;

然后你不会看到打印了两个不同的时间,而是打印了两次当前时间,因为两者都s1指向s2同一个字符串。

这同样适用于localtime,它返回一个指向struct tm- 但它总是相同的struct tm,所以如果你这样做:

struct tm* t1 = localtime(0);
struct tm* t2 = localtime(time()); 

您将在t1and中获得相同的值t2(使用“当前”时间,而不是 1970 年)。

所以,要解决这个问题,asctime_slocaltime_s有一个额外的参数用于存储数据。asctime_s还有第二个额外参数告诉函数存储缓冲区中有多少空间,否则可能会溢出该缓冲区。

于 2013-07-31T23:12:37.490 回答