gtpc2m58 | C/C++ Language Support User's Guide |
This function opens a directory so that it can be read with the readdir function.
Format
#include <dirent.h> DIR *opendir(const char *dirname);
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:
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.