我搜索我的Linux盒子,看到这样的类型定义:
typedef __time_t time_t;
但是我找不到__time_t的定义。
我搜索我的Linux盒子,看到这样的类型定义:
typedef __time_t time_t;
但是我找不到__time_t的定义。
当前回答
time_t类型定义最终是什么?
健壮的代码并不关心类型是什么。
C物种time_t为实类型,如double, long long, int64_t, int等。
它甚至可以是无符号的,因为许多时间函数的返回值表明错误不是-1,而是(time_t)(-1) -这种实现选择并不常见。
关键是“需要知道”的类型很少。代码的编写应该避免这种需要。
然而,当代码想要打印原始time_t时,会出现一个常见的“需要知道的问题”。转换为最宽的整数类型将适应大多数现代情况。
time_t now = 0;
time(&now);
printf("%jd", (intmax_t) now);
// or
printf("%lld", (long long) now);
转换为双精度或长双精度也可以,但可能提供不精确的十进制输出
printf("%.16e", (double) now);
其他回答
time_t维基百科的文章给出了一些解释。归根结底,在C规范中,time_t的类型是不保证的。
The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard header. ISO C defines time_t as an arithmetic type, but does not specify any particular type, range, resolution, or encoding for it. Also unspecified are the meanings of arithmetic operations applied to time values. Unix and POSIX-compliant systems implement the time_t type as a signed integer (typically 32 or 64 bits wide) which represents the number of seconds since the start of the Unix epoch: midnight UTC of January 1, 1970 (not counting leap seconds). Some systems correctly handle negative time values, while others do not. Systems using a 32-bit time_t type are susceptible to the Year 2038 problem.
在大多数传统平台上,它是一个32位有符号整数类型。然而,这会导致您的代码遭受2038年的错误。因此,现代C库应该将其定义为有符号的64位整型,这在几十亿年里是安全的。
您可以使用typeid来找出time_t在您的系统中是如何定义的。
#include <iostream> // cout
#include <ctime> // time_t
#include <typeinfo> // typeid, name
using namespace std;
int main()
{
cout << "Test 1: The type of time_t is: \t\t"
<< typeid(time_t).name() << endl;
cout << "Test 2: time_t is a signed long?: \t"
<< (typeid(time_t) == typeid(signed long) ? "true" : "false") << endl;
cout << "Test 3: time_t is an unsigned long?: \t"
<< (typeid(time_t) == typeid(unsigned long) ? "true" : "false") << endl;
return 0;
}
在我的系统中,输出是:
Test 1: The type of time_t is: l Test 2: time_t is a signed long?: true Test 3: time_t is an unsigned long?: false
通常,您将在bits或asm头目录中找到这些用于gcc的底层实现特定的typedefs。对我来说,是/usr/include/x86_64-linux-gnu/bits/types.h。
您可以只使用grep,或者使用Quassnoi建议的预处理器调用来查看哪个特定的头文件。
time_t类型定义最终是什么?
健壮的代码并不关心类型是什么。
C物种time_t为实类型,如double, long long, int64_t, int等。
它甚至可以是无符号的,因为许多时间函数的返回值表明错误不是-1,而是(time_t)(-1) -这种实现选择并不常见。
关键是“需要知道”的类型很少。代码的编写应该避免这种需要。
然而,当代码想要打印原始time_t时,会出现一个常见的“需要知道的问题”。转换为最宽的整数类型将适应大多数现代情况。
time_t now = 0;
time(&now);
printf("%jd", (intmax_t) now);
// or
printf("%lld", (long long) now);
转换为双精度或长双精度也可以,但可能提供不精确的十进制输出
printf("%.16e", (double) now);