Search code examples
linuxlibcstatfstat

file creation time system call in linux/gcc


As I know, stat/fstat system call tell us only 3 times about a file

  • Time of last access (st_atim field)
  • Time of last modification (st_mtim field)
  • Time of last status change (st_ctim)

and when I run stat filename command in bash, I can get creation time as Birth of the file. My question is, how can I get creation time in gcc by some system calls?


Solution

  • Use statx.

    From man 2 statx:

    SYNOPSIS #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> /* Definition of AT_* constants */

       int statx(int dirfd, const char *pathname, int flags,
                 unsigned int mask, struct statx *statxbuf);
    

    DESCRIPTION This function returns information about a file, storing it in the buffer pointed to by statxbuf. The returned buffer is a structure of the fol‐ lowing type:

           struct statx {
               __u32 stx_mask;        /* Mask of bits indicating
                                         filled fields */
               __u32 stx_blksize;     /* Block size for filesystem I/O */
               __u64 stx_attributes;  /* Extra file attribute indicators */
               __u32 stx_nlink;       /* Number of hard links */
               __u32 stx_uid;         /* User ID of owner */
               __u32 stx_gid;         /* Group ID of owner */
               __u16 stx_mode;        /* File type and mode */
               __u64 stx_ino;         /* Inode number */
               __u64 stx_size;        /* Total size in bytes */
               __u64 stx_blocks;      /* Number of 512B blocks allocated */
               __u64 stx_attributes_mask;
                                      /* Mask to show what's supported
                                         in stx_attributes */
    
               /* The following fields are file timestamps */
               struct statx_timestamp stx_atime;  /* Last access */
               struct statx_timestamp stx_btime;  /* Creation */
               struct statx_timestamp stx_ctime;  /* Last status change */
               struct statx_timestamp stx_mtime;  /* Last modification */
    

    That shows a field for a creation file stamp, appropriately named stx_btime (status extended birth time, I guess).

    Note that for Darwin (and presumably any BSD), stat() contains a field struct timespec st_birthtimespec already, and there is no statx().