Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

94 Files and Directories Chapter 4


Given apathname,thestatfunction returns a structure of information about the
named file. Thefstatfunction obtains information about the file that is already open
on the descriptorfd.Thelstatfunction is similar tostat,but when the named file is
asymbolic link, lstatreturns information about the symbolic link, not the file
referenced by the symbolic link. (We’ll needlstatin Section 4.22 when we walk down
adirectory hierarchy.Wedescribe symbolic links in moredetail in Section 4.17.)
Thefstatatfunction provides a way to return the file statistics for a pathname
relative to an open directory represented by the fdargument. The flag argument
controls whether symbolic links arefollowed; when theAT_SYMLINK_NOFOLLOWflag
is set,fstatatwill not follow symbolic links, but rather returns information about the
link itself. Otherwise, the default is to follow symbolic links, returning information
about the file to which the symbolic link points. If thefdargument has the value
AT_FDCWDand thepathnameargument is a relative pathname, thenfstatatevaluates
thepathnameargument relative to the current directory.Ifthepathnameargument is an
absolute pathname, then thefdargument is ignored. In these two cases,fstatat
behaves like eitherstatorlstat,depending on the value offlag.
Thebufargument is a pointer to a structurethat we must supply.The functions fill
in the structure. The definition of the structurecan differ among implementations, but
it could look like

struct stat {
mode_t st_mode; /* file type & mode (permissions) */
ino_t st_ino; /* i-node number (serial number) */
dev_t st_dev; /* device number (file system) */
dev_t st_rdev; /* device number for special files */
nlink_t st_nlink; /* number of links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
off_t st_size; /* size in bytes, for regular files */
struct timespec st_atim; /* time of last access */
struct timespec st_mtim; /* time of last modification */
struct timespec st_ctim; /* time of last file status change */
blksize_t st_blksize; /* best I/O block size */
blkcnt_t st_blocks; /* number of disk blocks allocated */
};

Thest_rdev,st_blksize,andst_blocksfields arenot required by POSIX.1. They are
defined as part of the XSI option in the Single UNIX Specification.

Thetimespecstructuretype defines time in terms of seconds and nanoseconds. It
includes at least the following fields:
time_t tv_sec;
long tv_nsec;

Prior to the 2008 version of the standard, the time fields werenamedst_atime,st_mtime,
andst_ctime,and were of typetime_t(expressed in seconds). Thetimespecstructure
enables higher-resolution timestamps. The old names can be defined in terms of thetv_sec
members for compatibility.For example,st_atimecan be defined asst_atim.tv_sec.
Free download pdf