Directories

There are a number of routines that relate to directories. As with other simple UNIX commands, they often have a close correspondence to the system calls that they call, as shown in Table 2.2.

The arguments passed to most directory operations is dependent on where in the file hierarchy the caller is at the time of the call, together with the pathname passed to the command:

Current working directory. This is where the calling process is at the time of the call; it can be obtained through use of pwd from the shell or getcwd() from within a C program.

Absolute pathname. An absolute pathname is one that starts with the character /. Thus to get to the base filename, the full pathname starting at / must be parsed. The pathname /etc/passwd is absolute.

Relative pathname. A relative pathname does not contain / as the first character and starts from the current working directory. For example, to reach the same passwd file by specifying passwd the current working directory must be /etc.

Table 2.2 Directory Related Operations

images

The following example shows how these calls can be used together:

$ cat dir.c #include <sys/stat.h> #include <sys/types.h> #include <sys/param.h> #include <fcntl.h> #include <unistd.h> main() { printf(“cwd = %s\n”, getcwd(NULL, MAXPATHLEN)); mkdir(“mydir”, S_IRWXU); chdir(“mydir”); printf(“cwd = %s\n”, getcwd(NULL, MAXPATHLEN)); chdir(“..”); rmdir(“mydir”); ...

Get UNIX Filesystems: Evolution, Design, and Implementation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.