Search code examples
linuxfile-iotimestampstat

How to read file time stamps in a Directory


I want to read the stat of all the files within a directory in C. (linux: Fedora)

i have declared this structure:

struct stat st = {0};  

Then I check for the existence of the directory.

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

where stat is:

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 */
};

now once i enter the directory I would want to check the last modification time st_mtime of each file.

Any ideas what data structure I should be using...should store the fd in a list first and then iterate over it checking... what is the efficient approach.

Thanks.


Solution

  • The generic approach is looping without any list like containers,

    1. Open fullpath of your dir dp = opendir(fullpath)) and get the directory pointer
    2. Loop by reading dp like this while ( (dirp = readdir(dp)) != NULL )
    3. Get the file names from the dirent structure dirp->d_name
    4. Construct a new full path for the filepahts i.e. smth like this filepath = fullpath + "/" + dirp->d_name
    5. and finally perform lstat to get the time-stamp info

    P.S. I would prefer to use lstat because one of the files in your directory might be a symbolic link, in this case lstat will return the timestamp of the symbolic link itself and not the timestamp of the file to which it points to