C Programs and Unix

Reading a Directory

DIR *opendir(char *name); Opens a directory and returns a handle that allows you to read the directory. Returns NULL if an error occurs.
struct dirent *readdir(DIR *d); Reads one entry from a directory. A struct dirent contains the field d_name.

readdir.c

Reading an Inode

int stat(char *pathname, struct stat *buffer) Reads information about a file from an inode and places it into a struct stat. Returns -1 on failure.

struct stat fields

st_dev>ID of device contaning file
st_inoThe inode number
st_modeThe file mode (including file type)
st_nlinkThe number of hard links to the file
st_uidThe uid of the file owner
st_gidThe gid of the file group
st_rdevThe device ID for a special file
st_blksizeThe preferred blocksize for I/O
st_blocksThe number of disk blocks allocated for the file
st_atimLast access time
st_mtimLast modified time
st_ctimLast status change time

Decoding Modes

The file type is encoded in the leftmost 4 bits of the sixteen bit mode. The header file defines the following bitmasks:

S_IFMTmask for the type field
S_IFSOCKunix domain socket
S_IFLNKsymbolic link
S_IFREGregular file
S_IFBLKblock device
S_IFDIRdirectory
S_IFCHRcharacter device
S_IFIFOFIFO

For example, if sb is a struct stat, we can do something based on the file type like this:

switch (sb.st_mode & S_IFMT) {
case S_IFREG: ... ; break;
case S_IFSOCK: ... ; break;
case S_IFDIR: ... ; break;
case S_IFSOCK: ... ; break;
...
}
To test for a single type, there is another collection of macros. For example, we could use S_ISDIR(sb.st_mode) to test for a directory.
S_ISSOCKunix domain socket
S_ISLNKsymbolic link
S_ISREGregular file
S_ISBLKblock device
S_ISDIRdirectory
S_ISCHRcharacter device
S_ISFIFOFIFO

Protection Bit Masks

S_ISUIDsetuid bit
S_ISGIDsetgid bit
S_ISVTXsticky bit
S_IRWXUOwner RWX
S_IRUSROwner R
S_IWUSROwner W
S_IXUSROwner X
S_IRWXGGroup RWX
S_IRGRPGroup R
S_IWGRPGroup W
S_IXGRPGroup X
S_IRWXOOthers RWX
S_IROTHOthers R
S_IWOTHOthers W
S_IXOTHOthers X

For example, to test whether owner write permission is on, we could do

if (sb.st_mode & S_IWUSR) { ... }

User Information

struct passwd *getpwnam(char *name);
struct passwd *getpwuid(uid_t uid);

struct passwd fields

pw_nameusername
pw_passwdpassword
pw_uid user ID
pw_gid group ID
pw_gecos user information
pw_dir home directory
pw_shell shell program

struct timespec Fields

time_t tv_sectime in seconds
time_t tv_nsecremainder time in nanoseconds

The function c_time can be applied to a time_t to give a string that is a human readable representation of the time.

fileinfo.c