【问题标题】:calculate difftime of two time-strings in c?计算c中两个时间字符串的差异时间?
【发布时间】: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,但您尚未检查。

标签: c string time time-t


【解决方案1】:

在每次调用 strptime() 之前清除 result

memset(&result, 0, sizeof result);
result.tm_isdst = -1;   // usually DST flag is unknown in the data just read
strptime(strncpy(buff_date, line+6, 19), "%c", &result);

result 中的未初始化垃圾正在搞乱localtime()

ref

这个函数原则上不初始化tm,只存储 指定的值。这意味着应该初始化 tm 通话前。


@Clifford 建议很好。如果文件数据是固定格式,请避免使用 "%c" 及其语言环境依赖项。


改进错误检查。检查strptime(), mktime()的结果。


次要:使用strncmp("start ", line, 6) 不会在line"start" 然后line+6 在字符串之后开始时发生strncmp("start", line, 5) 的UB。

【讨论】:

  • resultstrptime() 失败的任何情况下都不会被分配,如果语言环境时间格式与文件中使用的格式不匹配 - 这很可能。
  • @Clifford True - 最好检查函数返回值。
【解决方案2】:

如果您使用 Clifford 的答案将两行代码更改为: strptime(strncpy(buff_date, line + 6, 19), "%Y-%m-%d %H:%M:%S", &result); strptime(strncpy(buff_date, line + 5, 19), "%Y-%m-%d %H:%M:%S", &result); 那么你将有一个工作程序(但仍然没有适当的错误检查)。

【讨论】:

  • @chux-ReinstateMonica 你说得对,我更正了我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
相关资源
最近更新 更多