Datei-Baum-Scanner
#include <iostream.h>
extern "C" {
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
}
void printdir(const char *dir)
{
char fullname[256]; // path + name
// for opendir()
DIR *dir_pointer;
// for readdir()
// the function itself allocates the structure
// returns a pointer to it
struct dirent *dirent_pointer;
// for lstat()
// places the information in buffer which is allocated here
// needs the pointer to the buffer
struct stat statbuf;
dir_pointer = opendir(dir);
for (dirent_pointer = readdir(dir_pointer);
dirent_pointer != NULL; dirent_pointer = readdir(dir_pointer))
{
// skip current and parent dir
if ((!strcmp(dirent_pointer->d_name, ".")) ||
(!strcmp(dirent_pointer->d_name, "..")))
continue;
// build fullname
strcpy(fullname, dir);
strcat(fullname, "/");
strcat(fullname, dirent_pointer->d_name);
// get attributes of entry
if (!lstat(fullname, &statbuf))
{
cout << dir << "/" << dirent_pointer->d_name;
if (statbuf.st_mode & S_IFREG)
cout << " is a regular file" << endl;
else if (statbuf.st_mode & S_IFDIR)
{
cout << " is a directory" << endl;
printdir(fullname);
}
else
cout << " unkown type" << endl;
}
else
cerr << "Can't stat " << dir << "/" << dirent_pointer->d_name <<endl;
}
closedir(dir_pointer);
}
main()
{
char dir[] = "."; // start in current dir
printdir(dir);
}
© 1997 Gottfried Rudorfer, C++-AG, Lehrveranstaltungen, Abteilung für Angewandte Informatik, Wirtschaftsuniversität Wien, 3/19/1998 |