简体   繁体   English

c时间函数返回奇怪的值

[英]c-time function returns strange values

I'm working with a code in C, which gets the time from a server using the following: 我正在用C语言编写代码,它使用以下命令从服务器获取时间:

(This is a very short version, other sections and functions of the code use time, ftime and localtime functions to get the time). (这是一个非常简短的版本,代码的其他部分和函数使用time,ftime和localtime函数来获取时间)。

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? 有谁知道是什么原因导致这种行为或什么因素会影响使他们返回这些值的时间函数?

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() . 所有tm结构成员的类型均为int并且您在fprintf()为其使用了格式说明符%ld Instead, you should use %d format specifier. 相反,您应该使用%d格式说明符。

From C Standard#7.21.6.1p9 从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. 9如果转换规范无效,则行为是不确定的。282)如果任何参数不是对应转换规范的正确类型,则行为是不确定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM