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_ino | The inode number |
st_mode | The file mode (including file type) |
st_nlink | The number of hard links to the file |
st_uid | The uid of the file owner |
st_gid | The gid of the file group |
st_rdev | The device ID for a special file |
st_blksize | The preferred blocksize for I/O |
st_blocks | The number of disk blocks allocated for the file |
st_atim | Last access time |
st_mtim | Last modified time |
st_ctim | Last 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_IFMT | mask for the type field |
S_IFSOCK | unix domain socket |
S_IFLNK | symbolic link |
S_IFREG | regular file |
S_IFBLK | block device |
S_IFDIR | directory |
S_IFCHR | character device |
S_IFIFO | FIFO |
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_ISSOCK | unix domain socket |
S_ISLNK | symbolic link |
S_ISREG | regular file |
S_ISBLK | block device |
S_ISDIR | directory |
S_ISCHR | character device |
S_ISFIFO | FIFO |
Protection Bit Masks
S_ISUID | setuid bit |
S_ISGID | setgid bit |
S_ISVTX | sticky bit |
S_IRWXU | Owner RWX |
S_IRUSR | Owner R |
S_IWUSR | Owner W |
S_IXUSR | Owner X |
S_IRWXG | Group RWX |
S_IRGRP | Group R |
S_IWGRP | Group W |
S_IXGRP | Group X |
S_IRWXO | Others RWX |
S_IROTH | Others R |
S_IWOTH | Others W |
S_IXOTH | Others 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_name | username |
pw_passwd | password |
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_sec | time in seconds |
time_t tv_nsec | remainder 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