【问题标题】:Trouble using time_t to check time of last modification in C使用 time_t 检查 C 中最后修改时间的问题
【发布时间】:2012-04-25 23:43:06
【问题描述】:

所以我在 C 中实现 mtime 结构时遇到了麻烦,我试图检查文件的最后修改时间。编译时,我收到此错误:

pr8.1.c:246: error: incompatible types when assigning to type struct timespec from type time_t make: *** [pr8] Error 1

我使用的代码如下:

static struct timespec mtime(const char *file)
{
    struct stat s;
    struct timespec t = { 0, 0 };

    if (stat(file, &s) == 0)
#if     defined(MTIME) && MTIME == 1    // Linux
    { t = s.st_mtime; }
#elif   defined(MTIME) && MTIME == 2    // Mac OS X
    { t = s.st_mtimespec; }
#elif   defined(MTIME) && MTIME == 3    // Mac OS X, with some additional settings
    { t.tv_sec = s.st_mtime; t.tv_nsec = s.st_mtimensec; }
#else                                   // Solaris
    { t.tv_sec = s.st_mtime; }
#endif

    return t;
}

还有结构统计:

struct stat
{ time_t        st_mtime; };

附:对格式感到抱歉,我不确定为什么格式会这样。在 Linux 上运行它。提前感谢您的帮助。

【问题讨论】:

  • 作为提示,看看其他案例在做什么,并与您展示的struct stat sn-p 进行比较。 (其中一个已经在做正确的事了。)
  • 我想我理解你的意思,但是如果我删除stuct stat,我会收到一个编译时错误,即“s”的存储大小未初始化,我想我需要struct stat这个原因?
  • 不,你没有理解我的意思。与您引用的 st_mtime 类型相比,考虑其他案例的情况。
  • 我从底部的回复中了解到您现在的意思,谢谢您的回复。我认为 Linux 和那个版本的 Mac OS 不需要它。

标签: c linux time compiler-errors


【解决方案1】:

在 linux 和第一个 mac os x 版本中,您从 int (time_t) 分配给结构。在其他两个版本中,您正确地将 s 的成员分配给 t 的成员。如果改成这样,操作是否正确?

static struct timespec mtime(const char *file)
{
    struct stat s;
    struct timespec t = { 0, 0 };

    if (stat(file, &s) == 0)
#if     defined(MTIME) && MTIME == 1    // Linux
    { t.tv_sec = s.st_mtime; }
//     ^^^^^^^ 
#elif   defined(MTIME) && MTIME == 2    // Mac OS X
    { t.tv_sec = s.st_mtimespec; }
//     ^^^^^^^ 
#elif   defined(MTIME) && MTIME == 3    // Mac OS X, with some additional settings
    { t.tv_sec = s.st_mtime; t.tv_nsec = s.st_mtimensec; }
#else                                   // Solaris
    { t.tv_sec = s.st_mtime; }
#endif

    return t;
}

【讨论】:

  • 非常感谢,虽然我不确定我是否完全理解为什么。
【解决方案2】:

编译器告诉你类型不兼容,而且很明显。

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 2011-05-06
    • 1970-01-01
    • 2016-09-06
    • 2011-04-09
    • 2011-03-22
    • 2016-04-03
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多