gtpc2m5oC/C++ Language Support User's Guide

readdir-Read an Entry from a Directory

This function reads an entry from a directory.

Format

#include <dirent.h>
struct dirent *readdir(DIR *dir);

dir
A pointer to a dir object returned by the opendir function.

This function returns a pointer to a dirent structure describing the next directory entry in the directory stream associated with dir. A call to the readdir function overwrites data produced by a previous call to readdir on the same directory stream. Calls for different directory streams do not overwrite the data of each directory stream.

TPF deviation from POSIX

The TPF system does not support the atime (access time) time stamp.

A dirent structure contains character pointer d_name, which points to a string that gives the name of a file in the directory. This string ends in a terminating null and has a maximum of NAME_MAX characters.

Save the data from readdir, if required, before calling closedir because the closedir function frees the data.

Normal Return

If successful, the readdir function returns a pointer to a dirent structure describing the next directory entry in the directory stream. When the readdir function reaches the end of the directory stream, it returns a NULL pointer.

Error Return

If unsuccessful, the readdir function returns a NULL pointer and sets errno to the following:

EBADF
dir does not yield an open directory stream.

Programming Considerations

None.

Examples

The following example reads the contents of a root directory.

#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <stdio.h>
 
main() {
  DIR *dir;
  struct dirent *entry;
 
  if ((dir = opendir("/")) == NULL)
    perror("opendir() error");
  else {
    puts("contents of root:");
    while ((entry = readdir(dir)) != NULL)
      printf("  %s\n", entry->d_name);
    closedir(dir);
  }
}

Output

contents of root:
  .
  ..
  dev
  usr

Related Information

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.