stat and lstat
- stat is a function that populates a struct stat with information about some named file (regular files, directories, links).
- stat and lstat operate exactly the same way, except when the named file is a link, stat returns information about the file the link references, and lstat returns information about the link itself.
- Manual (man) pages exist for both of these functions (e.g. man 2 stat, man 2 lstat, etc.)
- The struct stat contain the following fields (source)
dev_t st_dev ID of device containing file
ino_t st_ino file serial number
mode_t st_mode mode of file
nlink_t st_nlink number of links to the file
uid_t st_uid user ID of file
gid_t st_gid group ID of file
dev_t st_rdev device ID (if file is character or block special)
off_t st_size file size in bytes (if file is a regular file)
time_t st_atime time of last access
time_t st_mtime time of last data modification
time_t st_ctime time of last status change
blksize_t st_blksize a filesystem-specific preferred I/O block size for
this object. In some filesystem types, this may
vary from file to file
blkcnt_t st_blocks number of blocks allocated for this object
- The st_mode field isn't so much a single value as it is a collection of bits encoding multiple pieces of information about file type and permissions.
- A collection of bit masks and macros can be used to extract information from the st_mode field.
- The next two examples—presented in these two slide decks—illustrate how the stat and lstat functions can be used to navigate and otherwise manipulate a tree of files within the file system.