c - 修改C中的时间函数

标签 c time casting

对于计算机安全作业,我必须修改时间函数以返回特定日期。我需要时间函数返回 2016 年 1 月 1 日和 2018 年 6 月 15 日之间的日期。然后我使用这些命令重载并连接到时间函数:

gcc -Wall -fPIC -shared -o newtime.so newtime.c -ldl
export LD_PRELOAD=$PWD/newtime.so

这是我修改后的时间函数:

#define _GNU_SOURCE

#include <dlfcn.h>
#include <time.h>

time_t time (time_t *t)
{
    long int seconds = 1485907200;
    time_t modifiedTime = (time_t) seconds;
    return modifiedTime;
}

每当我运行这个实现时,它都会说返回的日期是 1969 年 12 月 31 日 19:00:00。我只是错误地格式化了自 Linux Epoch 以来的时间,还是我犯了一个更严重的错误?我尝试使用常规 int 而不是 long int,但仍然遇到同样的问题。深入了解我的错误会很有帮助。

最佳答案

您没有实现 time() 的全部功能。您插入的代码可能会使用您尚未实现的功能。

Per the C standard :

7.27.2.4 The time function (note the bolded part):

Synopsis

     #include <time.h>
     time_t time(time_t *timer);

Description

The time function determines the current calendar time. The encoding of the value is unspecified.

Returns

The time function returns the implementation's best approximation to the current calendar time. The value (time_t)(-1) is returned if the calendar time is not available. If timer is not a null pointer, the return value is also assigned to the object it points to.

基于您的代码的完整实现:​​

time_t time (time_t *t)
{
    long int seconds = 1485907200;
    time_t modifiedTime = (time_t) seconds;

    if ( t )
    {
        *t = modifiedTime;
    }

    return modifiedTime;
}

关于c - 修改C中的时间函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54775930/

相关文章:

c - 使用函数 isAlphabetic 用 C 语言编写程序来确定字符串是否严格包含字母

c - C 中的段错误(代码转储)错误

Javascript 检查特定时间并返回 UTC 时区

C# 在发送前转换数组接口(interface)引用

java.lang.NumberFormatException : For input string: "0.10"

c - 第二个分离线程不打印消息

c - 在指针和函数指针之间进行类型转换时发出警告

Android小部件输入持续时间

c - NTP 客户端无限循环(不工作)

c# - 在作为数组的 ICollection 上调用 .toArray() 是否返回引用或副本?