In the 2nd edition of "The C Programming Language" by Kernighan and Ritchie they implement a simplified version of the UNIX command ls
(section 8.6 "Example - Listing Directories", p. 179). For this purpose they create the following interface which provides a system-independent access to the name and inode number of the files stored in a directory.
#define NAME_MAX 14 /* longest filename component; */
/* system dependent */
typedef struct { /* portable director-entry */
long ino; /* inode number */
char name[NAME_MAX+1]; /* name + '\0' terminator */
} Dirent;
typedef struct { /* minimal DIR: no buffering, etc. */
int fd; /* file descriptor for directory */
Dirent d; /* the directory entry */
} DIR;
DIR *opendir(char *dirname);
Dirent *readdir(DIR *dfd);
void closedir(DIR *dfd);
Then they implement this interface for Version 7 and System V UNIX systems.
opendir()
basically uses the system callopen()
to open a directory andmalloc()
to allocate space for aDIR
structure. The file descriptor returned byopen()
is then stored in the variablefd
of thatDIR
. Nothing is stored in theDirent
component.readdir()
uses the system callread()
to get the next (system-dependent) directory entry of an opened directory and copies the so obtained inode number and filename into a staticDirent
structure (to which a pointer is returned). The only information needed byreaddir()
is the file descriptor stored in theDIR
structure.
Now to my question: What is the point of having a DIR
structure? If my understanding of this program is correct, the Dirent
component of DIR
is never used, so why not replace the whole structure with a file descriptor and directly use open()
and close()
?
Thanks.
Ps: I am aware that on modern UNIX systems read()
can no longer be used on directories (I have tried out this program on Ubuntu 10.04), but I still want to make sure that I have not overlooked something important in this example.