【问题标题】:How to read file time stamps in a Directory如何读取目录中的文件时间戳
【发布时间】:2014-09-23 06:33:45
【问题描述】:

我想读取 C 目录中所有文件的统计信息。(linux:Fedora)

我已经声明了这个结构:

struct stat st = {0};  

然后我检查目录是否存在。

if(stat("/home/gadre/Source",&st) == -1)
{
    status = mkdir("/home/gadre/Source", 0777);             
}
syslog(LOG_INFO, "Source Directory stage completed\n");     

统计数据在哪里:

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 file system 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_mtime 每个文件。

任何想法我应该使用什么数据结构...应该首先将 fd 存储在一个列表中,然后对其进行迭代检查...什么是有效的方法。

谢谢。

【问题讨论】:

    标签: linux file-io timestamp stat


    【解决方案1】:

    通用的方法是在没有任何列表(如容器)的情况下循环,

    1. 打开您的目录dp = opendir(fullpath)) 的完整路径并获取目录指针
    2. 通过阅读dp 像这样while ( (dirp = readdir(dp)) != NULL ) 循环
    3. 从不同结构dirp->d_name获取文件名
    4. 为文件路径构造一个新的完整路径,即像这样filepath = fullpath + "/" + dirp->d_name
    5. 最后执行lstat获取时间戳信息

    附:我更喜欢使用lstat,因为您目录中的文件之一可能是符号链接,在这种情况下,lstat 将返回符号链接本身的时间戳,而不是它指向的文件的时间戳

    【讨论】:

    • 您好,谢谢,知道如何验证文件在之前的访问后是否已更新。例如:23-09-2014 文件已更新(修改),因此 st_atime、st_mtime 将更改为 23-09-2014。但 st_ctime 不是..因为 inode 信息将保持不变。 2014 年 9 月 25 日,文件被修改,因此 atime 和 mtime 被更改。但是,对于在 2014 年 9 月 26 日读取此统计信息的程序,它应该如何知道它已被修改
    • 很高兴知道这是一个解决方案,那么您可能可以接受答案。关于你的第二个问题,我记得st_atim是文件数据的最后一次访问时间,即表示何时被读取,st_mtim是文件数据的最后修改时间,即何时书面。因此,如果您仅使用 write 属性打开文件,则应仅修改 st_mtim
    猜你喜欢
    • 2017-10-25
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多