簡體   English   中英

c時間函數返回奇怪的值

[英]c-time function returns strange values

我正在用C語言編寫代碼,它使用以下命令從服務器獲取時間:

(這是一個非常簡短的版本,代碼的其他部分和函數使用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);
}

有時它工作得很好,但是有時候,當時間打印到文件中時,我得到的是這樣的:

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

有誰知道是什么原因導致這種行為或什么因素會影響使他們返回這些值的時間函數?

當地時間

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 */
};

所有tm結構成員的類型均為int並且您在fprintf()為其使用了格式說明符%ld 相反,您應該使用%d格式說明符。

從C Standard#7.21.6.1p9

9如果轉換規范無效,則行為是不確定的。282)如果任何參數不是對應轉換規范的正確類型,則行為是不確定的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM