Fausto
Fausto

Reputation: 3

c-time function returns strange values

I'm working with a code in C, which gets the time from a server using the following:

(This is a very short version, other sections and functions of the code use time, ftime and localtime functions to get the time).

struct  tm *stiempo;
long    ltiempo;
FILE * arch2;

int main()
{
  print_error_time();
}


void print_error_time()
{
   time (&ltiempo);
   stiempo = localtime (&ltiempo);
   fprintf (arch2, "%02.2ld/%02.2ld/%02.2ld, \t %02.2ld:%02.2ld:%02.2ld", stiempo->tm_mday, (stiempo->tm_mon + 1), (stiempo->tm_year + 1900), stiempo->tm_hour, stiempo->tm_min, stiempo->tm_sec);
}

Sometimes it works just fine, but sometimes, when the time is printed into the file, i get something like this:

   21/08/2018,   15:48:7956003943165722682
   21/08/2018,   15:50:7956003943165722667
   21/08/2018,   15:51:7956003943165722649

Does anyone knows what could be causing this beheaviour or what could affect the time functions that makes them return those values?

Upvotes: 0

Views: 90

Answers (1)

H.S.
H.S.

Reputation: 12644

From localtime:

Broken-down time is stored in the structure tm which is defined in <time.h> as follows:

struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
};

All the tm structure member are of type int and you are using format specifier %ld for them in fprintf(). Instead, you should use %d format specifier.

From C Standard#7.21.6.1p9

9 If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Upvotes: 3

Related Questions