How to scan a directory and list all files. You can use this code to write an application that will run some process on all the files under a directory tree.
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
static int isdir(char *path)
{
struct stat statbuf;
if (stat(path, &statbuf) == -1)
return 0;
return S_ISDIR(statbuf.st_mode);
}
static int recur(char *path, int indent)
{
DIR *dp;
struct dirent *dirp;
if (chdir(path) == -1)
{
perror(path);
return -1;
}
if ((dp = opendir(".")) == NULL)
return -1;
while ((dirp = readdir(dp)) != NULL)
{
if (isdir(dirp->d_name))
{
printf("%*s%s/\n", indent, "", dirp->d_name);
if (dirp->d_name[0] != '.')
recur(dirp->d_name, indent + 3);
}
else
printf("%*s%s\n", indent, "", dirp->d_name);
}
chdir("..");
closedir(dp);
return 0;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: dir <dirname>\n");
exit(1);
}
recur(argv[1], 0);
return 0;
}