Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

130 Files and Directories Chapter 4


#include <unistd.h>
int rmdir(const char *pathname);
Returns: 0 if OK,−1 on error
If the link count of the directory becomes 0 with this call, and if no other process has the
directory open, then the space occupied by the directory is freed. If one or more
processes have the directory open when the link count reaches 0, the last link is
removed and the dot and dot-dot entries areremoved beforethis function returns.
Additionally, no new files can be created in the directory.The directory is not freed,
however,until the last process closes it. (Even though some other process has the
directory open, it can’t be doing much in the directory, as the directory had to be empty
for thermdirfunction to succeed.)

4.22 Reading Director ies


Directories can be read by anyone who has access permission to read the directory.But
only the kernel can write to a directory, to preserve file system sanity.Recall from
Section 4.5 that the write permission bits and execute permission bits for a directory
determine if we can create new files in the directory and remove files from the
directory — they don’t specify if we can write to the directory itself.
The actual format of a directory depends on the UNIX System implementation and
the design of the file system. Earlier systems, such as Version 7, had a simple structure:
each directory entry was 16 bytes, with 14 bytes for the filename and 2 bytes for the
i-node number.When longer filenames wereadded to 4.2BSD, each entry became
variable length, which means that any program that reads a directory is now system
dependent. Tosimplify the process of reading a directory,aset of directory routines
weredeveloped and arepart of POSIX.1. Many implementations prevent applications
from using thereadfunction to access the contents of directories, thereby further
isolating applications from the implementation-specific details of directory formats.
#include <dirent.h>
DIR *opendir(const char *pathname);
DIR *fdopendir(intfd);
Both return: pointer if OK,NULLon error
struct dirent *readdir(DIR *dp);
Returns: pointer if OK,NULLat end of directory or error
void rewinddir(DIR *dp);
int closedir(DIR *dp);
Returns: 0 if OK,−1 on error
long telldir(DIR *dp);
Returns: current location in directory associated withdp
void seekdir(DIR *dp,long loc);
Free download pdf