Linux目录扫描程序

Linux目录扫描程序
//功能函数,递归遍历指定目录。
void printdir(char *dir, int depth)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;

    //打开指定目录建立目录流
    if ((dp = opendir(dir)) == NULL) {
       fprintf(stderr, "Can't 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 directory, 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, depty+4);
       }
       else
          printf("%*s%s\n", depth, " ", entry->d_name);
    }
    chdir("..");
    closedir(dp);
}

//main函数
int main(int argc, char *argv[])
{
    char *topdir = ".";
    if (argc >= 2)
       topdir = argv[1];

    printf("Directory scan of %s\n", topdir);
    printdir(topdir, 0);
    printf("done.\n");

    exit(0);
}

PS.程序实现递归遍历指定的目录内容
若目标程序名为"printdir",则可通过以下命令运行:
$ printdir /usr/local | more
输出结果将分页显示。
我们可以此为基础,对之进行有效扩充,以实现更强大实用且通用
的程序。

你可能感兴趣的:(Linux目录扫描程序)