robojames
robojames

Reputation: 1

calculate difftime of two time-strings in c?

I have a file like this:

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

Now Im trying to write a code which calculates the time difference between a start and end time. This is my code so far.

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
        }   
    }

My problem is that I always get as result this:

Difference is  0.00 seconds
Difference is  0.00 seconds
Difference is  0.00 seconds

Can someone help me to find the bug or can someone tell me how I can do this in a better way?

Upvotes: 0

Views: 153

Answers (2)

AvD
AvD

Reputation: 153

If you use Clifford's answer to change two code lines into: 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); then you will have a working program (but still without proper error checking).

Upvotes: 0

chux
chux

Reputation: 153338

Clear result before each strptime() call.

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);

Uninitialized garbage in result is messing localtime().

ref

In principle, this function does not initialize tm but stores only the values specified. This means that tm should be initialized before the call.


@Clifford advice is good. If file data is a fixed format, avoid "%c" with its locale dependencies.


Improve error checking. Check results of strptime(), mktime().


Minor: use strncmp("start ", line, 6) to not incur UB with strncmp("start", line, 5) that occurs when line is "start" and then line+6 starts after the string.

Upvotes: 1

Related Questions