Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1 |
both |
#define _POSIX_SOURCE
#include <dirent.h>
DIR *opendir(const char *dirname);
Opens a directory so that it can be read with readdir() or __readdir2(). dirname is a string giving the name of the directory you want to open. The first readdir() or __readdir2() call reads the first entry in the directory.
If successful, opendir() 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 I/O operations.
⁄* CELEBO01
This example opens a directory.
*⁄
#define _POSIX_SOURCE
#include <dirent.h>
#include <errno.h>
#include <sys⁄stat.h>
#include <sys⁄types.h>
#undef _POSIX_SOURCE
#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("⁄etc", 0);
}
Directory structure:
/etc
/etc/samples
/etc/samples/IBM
/etc/IBM