Directories


#include <sys/types.h>
#include <dirent.h>

DIR * opendir (const char *dirname);
struct dirent * readdir (DIR *dirstream);
int closedir (DIR *dirstream);

Opening and Closing a Directory Stream

The opendir function opens and returns a directory stream for reading the directory whose file name is dirname. The stream has type DIR *. If unsuccessful, opendir returns a null pointer.

The closedir function closes the directory stream dirstream. It returns 0 on success and -1 on failure.

Reading a Directory Stream

The readdir function reads the next entry from the directory. It normally returns a pointer to a structure containing information about the file. This structure is statically allocated and can be rewritten by a subsequent call. If there are no more entries in the directory or an error is detected, readdir returns a null pointer.

Portability Note: On some systems readdir may not return entries for . and .., even though these are always valid file names in any directory.

Format of a Directory Entry

The data type struct dirent is used to return information about directory entries. It contains the following fields:

MemberDescription
char d_name[]file name
ino_t d_filenofile serial number
unsigned char d_namlenfile name length
unsigned char d_typefile type

When a file has multiple names, each name has its own directory entry. The only way you can tell that the directory entries belong to a single file is that they have the same value for the d_fileno field.

File attributes such as size, modification times etc., are part of the file itself, not of any particular directory entry. See File Attributes.

File Type

The following constants are defined for file type:

DT_UNKNOWNunknown
DT_REGA regular file.
DT_DIRA directory.
DT_FIFOA named pipe, or FIFO.
DT_SOCKA local-domain socket.
DT_CHRA character device.
DT_BLKA block device.

References

Accessing Directories (from the GNU C Library Reference Manual).

Neil Matthew and Richard Stone, Beginning Linux Programming, Third Edition,
Wrox, 2004. ISBN 0-7645-4497-7. p 120-125.

W. Richard Stevens and Stephen A. Rago, Advanced Programming in the UNIX Environment, Second Edition, Addison Wesley, 2005. ISBN 0-201-43307-9.


Maintained by John Loomis, last updated 4 September 2006