void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp=opendir(dir))==NULL){
fprintf(stderr,"cannot open directory: %s\n",dir);
return;
}
chdir(dir);
while((entry=readdir(dp))!=NULL){
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode)){
/* found a dirent, but ignore , and .. */
if(strcmp(".",entry->d_name)==0||
strcmp("..",entry->d_name)==0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else
printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
void scandir(char *dirname)
{
DIR *dir;
struct dirent *ent;
printf("First pass on '%s':\n",dirname);
if ((dir = opendir(dirname)) == NULL)
{
perror("Unable to open directory");
exit(1);
}
while ((ent = readdir(dir)) != NULL)
printf("%s\n",ent->d_name);
printf("Second pass on '%s':\n",dirname);
rewinddir(dir);
while ((ent = readdir(dir)) != NULL)
printf("%s\n",ent->d_name);
if (closedir(dir) != 0)
perror("Unable to close directory");
}