这完全取决于时间戳需要采用的格式和分辨率,正如 cmets 中所指出的那样。
要构建一个通用方法,查看 C 的 date and time utilities 很有用。如果这不符合您的要求,那么您必须寻找第三方库。无论哪种方式,您的程序的基本结构很可能是相同的。
这是 C11 中的一个基本示例(睡眠功能除外)。它打印结构、设置时间戳和休眠。之后它会打印存储的时间戳。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAY_SIZE 20
#define STRUCT_STRING_SIZE 65
struct St
{
time_t timestamp;
char aps[STRUCT_STRING_SIZE];
};
void nanosleepWrapper(void);
time_t timeWrapper(void);
int main(void)
{
struct St arr[ARRAY_SIZE];
// Fill structs array with placeholder data
for (size_t idx = 0U; idx < ARRAY_SIZE; ++idx)
snprintf(arr[idx].aps, STRUCT_STRING_SIZE, "Placeholder value %zu", idx);
// Loop: print struct data, set timestamp, and sleep
for (size_t idx = 0U; idx < ARRAY_SIZE; ++idx)
{
printf("%s\n", arr[idx].aps);
fflush(stdout);
nanosleepWrapper();
arr[idx].timestamp = timeWrapper();
}
// Print all timestamps
for (size_t idx = 0U; idx < ARRAY_SIZE; ++idx)
printf("%zu: %s", idx, asctime(gmtime(&arr[idx].timestamp)));
}
// Sleep using a function which is not standard C, but is POSIX
void nanosleepWrapper(void)
{
struct timespec req = {0, 500000000};
if (nanosleep(&req, NULL) == -1)
fprintf(stderr, "Sleep failed\n");
}
time_t timeWrapper(void)
{
time_t tmp = time(NULL);
if (tmp == (time_t)(-1))
{
fprintf(stderr, "Setting timestamp failed\n");
exit(EXIT_FAILURE);
}
return tmp;
}
示例输出:
Placeholder value 0
Placeholder value 1
Placeholder value 2
...
Placeholder value 18
Placeholder value 19
0: Wed Sep 1 11:18:04 2021
1: Wed Sep 1 11:18:05 2021
2: Wed Sep 1 11:18:05 2021
...
18: Wed Sep 1 11:18:13 2021
19: Wed Sep 1 11:18:14 2021