Chapter 23. Directories

Filesystem operations all take a directory pointer as one of their arguments. A directory pointer is an opaque handle managed by the filesystem. It should encapsulate a reference to a specific directory within the filesystem. For example, it may be a pointer to the data structure that represents that directory (such as an inode), or a pointer to a pathname for the directory.

The chdir() filesystem function pointer has two modes of use. When passed a pointer in the dir_out argument, it should locate the named directory and place a directory pointer there. If the dir_out argument is NULL then the dir argument is a previously generated directory pointer that can now be disposed of. When the infrastructure is implementing the chdir() function it makes two calls to filesystem chdir() functions. The first is to get a directory pointer for the new current directory. If this succeeds the second is to dispose of the old current directory pointer.

The opendir() function is used to open a directory for reading. This results in an open file object that can be read to return a sequence of struct dirent objects. The only operations that are allowed on this file are read, lseek and close. Each read operation on this file should return a single struct dirent object. When the end of the directory is reached, zero should be returned. The only seek operation allowed is a rewind to the start of the directory, by supplying an offset of zero and a whence specifier of SEEK_SET.

Most of these considerations are invisible to clients of a filesystem since they will access directories via the POSIX opendir(), readdir() and closedir() functions. The struct dirent object returned by readdir() will always contain d_name as required by POSIX. When CYGPKG_FILEIO_DIRENT_DTYPE is enabled it will also contain d_type, which is not part of POSIX, but often implemented by OSes. Currently only the FATFS, RAMFS, ROMFS and JFFS2 filesystem sets this value. For other filesystems a value of 0 will be returned in the member.

Support for the getcwd() function is provided by three mechanisms. The first is to use the FS_INFO_GETCWD getinfo key on the filesystem to use any internal support that it has for this. If that fails it falls back on one of the two other mechanisms. If CYGPKG_IO_FILEIO_TRACK_CWD is set then the current directory is tracked textually in chdir() and the result of that is reported in getcwd(). Otherwise an attempt is made to traverse the directory tree to its root using ".." entries.

This last option is complicated and expensive, and relies on the filesystem supporting "." and ".." entries. This is not always the case, particularly if the filesystem has been ported from a non-UNIX-compatible source. Tracking the pathname textually will usually work, but might not produce optimum results when symbolic links are being used.

Documentation license for this page: Open Publication License