DispencedTaco
DispencedTaco

Reputation: 33

Inconsistent parsing with strptime in C?

Im encountering strange behavior when trying to use the strptime function in C.

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

I run this program as ./timetest 2400/001/00/00/00 2400/001/00/00/08

Heres some terminal output:

$ ./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

Is there something that I am missing that will produce these inconsistent results?

Upvotes: 3

Views: 149

Answers (1)

uzr
uzr

Reputation: 1210

Could be that tm is not initialized before the use of strptime.

Initialize tm: memset(&tm, 0, sizeof(struct tm));

Documentation states that tm does not generally gets initialized before called by strptime. It depends on which implementation/UNIX system that you are using.

Upvotes: 1

Related Questions