Get Unix epoch seconds with time and time_t
Read the current Unix epoch seconds with time(NULL) on glibc 2.41, and build 32-bit targets with _TIME_BITS=64 so time_t survives the year 2038.
time(NULL) returns the number of seconds since 1970-01-01 00:00:00 UTC, as a time_t. The call is simple. The part that bites is the width of time_t, which is 64 bits on x86-64 and arm64 but 32 bits by default on 32-bit Linux, where it overflows in January 2038.
#include <stdio.h>
#include <time.h>
int main(void) {
time_t now = time(NULL);
printf("sizeof(time_t) = %zu\n", sizeof now);
printf("epoch = %lld\n", (long long)now);
return 0;
}sizeof(time_t) = 8
epoch = 1795442709The epoch value will differ on your machine. Cast to long long before printing, because there is no portable printf length modifier for time_t.
On a 32-bit target, glibc 2.34 and later let you ask for the 64-bit type with -D_TIME_BITS=64, which must be paired with -D_FILE_OFFSET_BITS=64, as explained in the glibc manual. Mixing objects built with different values of the flag changes struct layouts, so set it for every file of a build and every library you link, not just one.
time has one-second resolution and follows the wall clock, so it jumps when someone sets the date. For elapsed time use clock_gettime(CLOCK_MONOTONIC, ...) instead.