---
title: "UNIX目录扫描"
author: "vergilwang"
date: "2011-11-04T17:09:00Z"
tags: []
categories: ["编程语言"]
slug: "unix"
draft: false
lastmod: "2014-02-15T16:26:09Z"
id: 2011429
url: "https://vergilwang.iteye.com/blog/2011429"
---

/*  
\* =====================================================================================  
\*  
\* Filename: printdir.c  
\*  
\* Description:  
\*  
\* Version: 1.0  
\* Created: 2011年11月04日 13时43分18秒  
\* Revision: none  
\* Compiler: gcc  
\*  
\* Author: Wang Ran (), wangran51@126.com  
\* Company:  
\*  
\* =====================================================================================  
\*/

#include &lt;dirent.h&gt;  
#include &lt;string.h&gt;  
#include &lt;sys/stat.h&gt;  
#include &lt;stdlib.h&gt;  
#include &lt;stdio.h&gt;

void printdir(char \*dir, int depth)  
{  
DIR \*dp;  
struct dirent \*entry;  
struct stat statbuf;

if ((dp = opendir(dir)) == NULL)  
{  
fprintf(stderr, "can not directory: %s\\n", dir);  
return ;  
}  
chdir(dir);  
while ((entry = readdir(dp)) != NULL)  
{  
lstat (entry-&gt;d\_name, &statbuf);  
if (S\_ISDIR(statbuf.st\_mode))  
{  
if (strcmp(".", entry-&gt;d\_name) == 0 ||  
strcmp("..", entry-&gt;d\_name) == 0)  
{  
continue;  
}  
printf("%\*s%s\\n", depth, "", entry-&gt;d\_name);  
printdir(entry-&gt;d\_name, depth+4);//recurse at new indent level  
}  
else  
{  
printf("%\*s%s\\n", depth, "", entry-&gt;d\_name);  
}  
}  
chdir("..");  
closedir(dp);  
}

int main()  
{  
printf("Directory scan of /home :\\n");  
printdir("/home/vergil/C/", 0);  
printf("done");  
}