【问题标题】:How to get last modified time of a file in OS X/ C?如何在 OS X/C 中获取文件的最后修改时间?
【发布时间】:2016-03-25 04:13:49
【问题描述】:

我有以下代码:

struct stat info;
stat("/Users/john/test.txt", &info);
printf("%s\n", ctime(&info.st_mtimespec));

我试图获取文件的最后修改时间,如ls -l 命令中显示的格式:

Jan 29 19:39

不幸的是,上面的代码不起作用。我在 xcode 上收到以下错误消息:

Conflicting types for ctime

我该如何解决?如果有任何替代方法来获取提到的格式时间,请提及。

【问题讨论】:

  • 它“不起作用”是因为?
  • 我收到 ctime 函数的“冲突类型”错误消息
  • 您不认为在问题中提及这一点有意义吗?请编辑您的问题以输入确切的错误消息。
  • Jenna,您会惊讶于错误消息提供一些关于正在发生什么问题的提示的频率。
  • @ghoti 我理解问题-ctime 没有得到它需要的参数。我遇到的问题是要插入什么东西....

标签: c macos date unix


【解决方案1】:

检查struct stat 的声明,您会发现st_mtimespec 必须是st_mtime

然后,基于这个question,我重新排列了你的代码:

struct stat info;
struct tm* tm_info;
char buffer[16];

stat("/Users/john/test.txt", &info);
tm_info = localtime(&info.st_mtime);
strftime(buffer, sizeof(buffer), "%b %d %H:%M", tm_info);

printf("%s\n", buffer);

希望对你有帮助。

【讨论】:

    【解决方案2】:

    我相信这就是您正在寻找的:

    #include <sys/stat.h>
    #include <time.h>
    
    int main(int argc, char *argv[])
    {
        struct stat info;
        stat("sample.txt", &info);
        printf("%.12s\n", 4+ctime(&info.st_mtimespec));
        return 0;
    }
    

    输出(与ls -l的时间字段相同):

    Feb  4 00:43
    

    (这是我电脑上的一个随机文件)。

    【讨论】:

      【解决方案3】:

      你的代码有:

      #include <time.h>
      

      另外,ctime() 函数期望传递的参数是指向time_t 的指针。

      这是stat()函数指向的结构体:

                struct stat {
                 dev_t     st_dev;     /* ID of device containing file */
                 ino_t     st_ino;     /* inode number */
                 mode_t    st_mode;    /* protection */
                 nlink_t   st_nlink;   /* number of hard links */
                 uid_t     st_uid;     /* user ID of owner */
                 gid_t     st_gid;     /* group ID of owner */
                 dev_t     st_rdev;    /* device ID (if special file) */
                 off_t     st_size;    /* total size, in bytes */
                 blksize_t st_blksize; /* blocksize for filesystem I/O */
                 blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
                 time_t    st_atime;   /* time of last access */
                 time_t    st_mtime;   /* time of last modification */
                 time_t    st_ctime;   /* time of last status change */
             };
      

      请注意,所有字段都不是st_mtimespec

      也许你的意思是st_mtime

      注意:你运行的 OS-X 和我运行的 linux,但 OS-X 的字段名称定义应该完全相同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-05
        • 1970-01-01
        • 2012-05-13
        • 1970-01-01
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        • 2017-03-23
        相关资源
        最近更新 更多