gtpc2m58C/C++ Language Support User's Guide

opendir-Open a Directory

This function opens a directory so that it can be read with the readdir function.

Format

#include <dirent.h>
DIR *opendir(const char *dirname);

dirname
The name of the directory to be opened.

The first readdir function call reads the first entry in the directory. The second readdir function call reads the second entry in the directory, and so on. You can only read a directory sequentially.

Normal Return

If successful, the opendir function returns a pointer to a DIR object. This object describes the directory and is used in subsequent operations on the directory in the same way that FILE objects are used in file input/output (I/O) operations.

Error Return

If unsuccessful, the opendir function returns a NULL pointer and sets errno to one of the following:

EACCES
The process does not have permission to search some component of dirname or it does not have read permission on the directory itself.

ELOOP
A loop exists in the symbolic links. This error is issued if the number of symbolic links found while resolving the dirname argument is greater than POSIX_SYMLOOP.

EMFILE
The process has too many other file descriptors open.

ENAMETOOLONG
pathname is longer than PATH_MAX characters or some component of pathname is longer than NAME_MAX characters. For symbolic links, the length of the path name string substituted for a symbolic link exceeds PATH_MAX.

ENFILE
The entire system has too many other file descriptors open.

ENOENT
The dirname directory does not exist.

ENOTDIR
Some component of the dirname path name is not a directory.

Programming Considerations

None.

Examples

The following example opens a directory.

#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
 
void traverse(char *fn, int indent) {
  DIR *dir;
  struct dirent *entry;
  int count;
  char path[1025];
  struct stat info;
 
  for (count=0; count<indent; count++) printf("  ");
  printf("%s\n", fn);
 
  if ((dir = opendir(fn)) == NULL)
    perror("opendir() error");
  else {
    while ((entry = readdir(dir)) != NULL) {
      if (entry->d_name[0] != '.') {
        strcpy(path, fn);
        strcat(path, "/");
        strcat(path, entry->d_name);
        if (stat(path, &info) != 0)
          fprintf(stderr, "stat() error on %s: %s\n", path,
                  strerror(errno));
        else if (S_ISDIR(info.st_mode))
               traverse(path, indent+1);
      }
    }
    closedir(dir);
  }
}
 
main() {
  puts("Directory structure:");
  traverse("/dev", 0);
}

Output

Directory structure:
  /dev
    /dev/null
    /dev/tpf.omsg
    /dev/tpf.imsg
    /dev/tpf.socket.file

Related Information

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