我在尝试使用C语言中的strptime函数时遇到了奇怪的行为。
#include <stdio.h>
#define __USE_XOPEN
#define _GNU_SOURCE
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
int parseTime(char *timestamp)
{
time_t t1;
struct tm *timeptr,tm1;
char* time1 = timestamp;
//(1) convert `String to tm`:
if(strptime(time1, "%Y/%j/%H/%M/%S",&tm1) == 0)
{
fprintf(stderr,"\nInvalid timestamp\nTimestamp should be in the format: YYYY/DDD/HH/MM/SS\n");
exit(EXIT_FAILURE);
}
//(2) convert `tm to time_t`:
t1 = mktime(&tm1);
return t1;
}
int main(int argc, char const *argv[])
{
int now = parseTime(argv[1]);
int wait = parseTime(argv[2]) - now;
printf("%d\n", wait);
return 0;
}
我以./timetest 2400/001/00/00/00 2400/001/00/00/08的形式运行这个程序
以下是一些终端输出:
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
3608
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
3608
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
8
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
8
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
8
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
8
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
3608
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
3608
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
8
$ ./timetest 2400/001/00/00/00 2400/001/00/00/08
3608
有没有什么我遗漏的东西会导致这些不一致的结果?
发布于 2017-02-28 14:14:32
可能是在使用strptime
之前未初始化tm
。
初始化tm:memset(&tm, 0, sizeof(struct tm));
Documentation指出,在被strptime
调用之前,tm
通常不会初始化。这取决于您使用的实现/UNIX系统。
https://stackoverflow.com/questions/42501161
复制相似问题