如何在操作系统X/C中获取文件的最后修改时间



我有以下代码:

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

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

Jan 29 19:39

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

Conflicting types for ctime

我该怎么修?如果有任何其他方法可以按照提到的格式获得时间,请务必提及。

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

然后,基于这个问题,我重新排列了你的代码如下:

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("%sn", buffer);

希望能有所帮助。

我相信这就是您想要的:

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

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

Feb  4 00:43

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

您的代码有吗

#include <time.h>

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

以下是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应该具有相同的字段名称定义。

最新更新