本文主要就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(¤t_time, NULL);
fprintf(stdout, "current time stamp: %" PRId64 "\n", current_time.tv_sec);