【C語言】時間結構體

本文主要就C語言中常用類型time_t具體分析。

一、定義

首先來看一下定義,原來是一種類型重命名。

/* File: /usr/include/time.h */
typedef __time_t time_t;

庫文件中使用的其實是__time_t這個命名。

/* File: /usr/include/bits/time.h */
struct timeval
{
    __time_t tv_sec;        /* Seconds.  */
    __suseconds_t tv_usec;  /* Microseconds.  */
};

接着看進一步的定義

/* File: /usr/include/bits/types.h */
__STD_TYPE __TIME_T_TYPE __time_t;  /* Seconds since the Epoch.  */
__STD_TYPE __USECONDS_T_TYPE __useconds_t; /* Count of microseconds.  */
__STD_TYPE __SUSECONDS_T_TYPE __suseconds_t; /* Signed count of microseconds.  */
/* File: /usr/include/bits/typesizes.h */
#define __TIME_T_TYPE       __SLONGWORD_TYPE
#define __USECONDS_T_TYPE   __U32_TYPE
#define __SUSECONDS_T_TYPE  __SLONGWORD_TYPE
/* File: /usr/include/bits/types.h */
#define __S16_TYPE      short int
#define __U16_TYPE      unsigned short int
#define __S32_TYPE      int
#define __U32_TYPE      unsigned int
#define __SLONGWORD_TYPE    long int
#define __ULONGWORD_TYPE    unsigned long int

二、使用場景

time_t類型的值如果想在printf中打印,使用格式符PRId64,該格式符定義包含在頭文件inttypes.h中。

#include <inttypes.h>

struct timeval current_time;
gettimeofday(&current_time, NULL);
fprintf(stdout, "current time stamp: %" PRId64 "\n", current_time.tv_sec);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章