【发布时间】:2020-05-01 17:05:49
【问题描述】:
我有一个这样的文件:
start 2020-01-13 02:43:39
ende 2020-01-13 02:44:26
start 2020-01-13 02:50:24
ende 2020-01-13 02:50:26
start 2020-01-13 02:50:24
ende 2020-01-13 02:50:26
现在我正在尝试编写一个代码来计算开始时间和结束时间之间的时间差。 这是我目前的代码。
char * line = NULL;
size_t len = 0;
char * command = malloc(MAXCHAR * sizeof(char));
struct tm result;
time_t loctime, loc;
char *buff_date = malloc(30);
int s=0, e=0;
while (getline(&line, &len, fp) != -1) { //go trough file and read it line by line
if(strncmp("start", line, 5) == 0){ //start
strptime(strncpy(buff_date, line+6, 19), "%c", &result);
buff_date[19] = '\0';
s=1; //start command was found
loc = mktime(&result);
} else if(strncmp("ende", line, 4) == 0){ //end
strptime(strncpy(buff_date, line+5, 18), "%c", &result);
buff_date[19] = '\0';
e=1; //end command was found
loctime = mktime(&result);
}
if(s == 1 && e == 1){ //I have a command and a start, now calculate diff time
printf("Difference is %.2f seconds\n", difftime(loctime, loc));
s = 0;//reset
e = 0; //reset
}
}
我的问题是我总是得到这样的结果:
Difference is 0.00 seconds
Difference is 0.00 seconds
Difference is 0.00 seconds
谁能帮我找到错误,或者谁能告诉我如何以更好的方式做到这一点?
【问题讨论】:
-
为什么是
buff_data[19] = '\0';?strptime(strncpy(buff_date, line+6, 19)发生了什么?为什么不只是strptime(line + 6? -
%c需要时间为区域设置的首选格式 - 您确定它与您的文件格式匹配吗?无论如何,如果文件格式是固定的,您不希望解析是特定于语言环境的。为什么不"%Y-%m-%d %H:%M:%S"?strptime()在匹配失败时返回 NULL,但您尚未检查。