【问题标题】:Timestamp inside structure in cc中结构内部的时间戳
【发布时间】:2021-08-31 19:32:32
【问题描述】:

如何创建结构以在其中包含时间戳?我想创建结构数组,每次打印数组的一个元素时,我都想要时间戳(我想在结构 St 内部实现)和字符串。

struct St{
char Aps[65];
};

struct S1 Arr[20];

【问题讨论】:

  • 您希望时间戳采用什么格式?
  • 取决于您正在寻找的分辨率。如果一秒的分辨率足够好,并且你不关心 2100 年后的时间戳,那么一个简单的无符号 32 位数字就可以了,你可以通过调用 time 函数来获取时间戳。跨度>
  • 我也有同样的问题......但我想用它作为 NAT 表销毁计时器,在表结构中,格式将在几秒钟内
  • 考虑制作一个ISO8601 时间戳,因为标准!不幸的是,该语言早于标准,所以这在 C 中是不平凡的。

标签: c


【解决方案1】:

这完全取决于时间戳需要采用的格式和分辨率,正如 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    相关资源
    最近更新 更多