0
我有一个简单的函数(我猜是因为某些错误的指针分配)的问题。由于strptime
函数(一个函数接受一个字符串并返回一个带有所有数据集的struct tm
)在Windows中不存在,我通过调用其他基本工作函数创建了一种strptime函数。指向结构tm变量的指针,不能回复更改
以下是测试代码。在STRPTIME功能里面,时间设定的很好,然后主要我失去了信息。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void STRPTIME(char *strtm, struct tm *tminfo)
{
time_t rawtime;
int day, month, year;
sscanf(strtm, "%d-%d-%d\n", &year, &month, &day);
time(&rawtime);
tminfo = localtime(&rawtime);
tminfo->tm_year = year - 1900;
tminfo->tm_mon = month - 1;
tminfo->tm_mday = day;
mktime(tminfo);
printf("date %d-%d-%d\n", tminfo->tm_year, tminfo->tm_mon, tminfo->tm_mday);
}
int main()
{
char stm[11];
struct tm tminfo;
strcpy(stm, "2015-12-31");
STRPTIME(stm, &tminfo);
printf("tminfo %d-%d-%d\n", tminfo.tm_year, tminfo.tm_mon, tminfo.tm_mday);
return(0);
}
你是完全正确的!我没有想到它! 'if'是一个检查,以确保本地时间返回不是'NULL',并且输入是'NULL',对吧? – Stefano
顺便说一句,这个解决方案是否是一个很好的解决问题的方法,或者有更有趣的方法,最重要的是更快? – Stefano
是的,'if'确保'localtime'的结果和函数的参数不是'NULL',因为'memcpy'的两个参数不能是'NULL'。由于你的'strptime'版本没有'format'参数,所以它并不是真的等价。所以它是否“足够好”可能取决于你的用例。另见[这个问题](http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows)。 – DarkDust