UNIX目录扫描
/*
?* =====================================================================================
?*
?* ? ? ? Filename: ?printdir.c
?*
?* ? ?Description: ?
?*
?* ? ? ? ?Version: ?1.0
?* ? ? ? ?Created: ?2011年11月04日 13時(shí)43分18秒
?* ? ? ? Revision: ?none
?* ? ? ? Compiler: ?gcc
?*
?* ? ? ? ? Author: ?Wang Ran (), wangran51@126.com
?* ? ? ? ?Company: ?
?*
?* =====================================================================================
?*/
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
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->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode))
{
if (strcmp(".", entry->d_name) == 0 ||
strcmp("..", entry->d_name) == 0)
{
continue;
}
printf("%*s%s\n", depth, "", entry->d_name);
printdir(entry->d_name, depth+4);//recurse at new indent level
}
else
{
printf("%*s%s\n", depth, "", entry->d_name);
}
}
chdir("..");
closedir(dp);
}
int main()
{
printf("Directory scan of /home :\n");
printdir("/home/vergil/C/", 0);
printf("done");
}
?* =====================================================================================
?*
?* ? ? ? Filename: ?printdir.c
?*
?* ? ?Description: ?
?*
?* ? ? ? ?Version: ?1.0
?* ? ? ? ?Created: ?2011年11月04日 13時(shí)43分18秒
?* ? ? ? Revision: ?none
?* ? ? ? Compiler: ?gcc
?*
?* ? ? ? ? Author: ?Wang Ran (), wangran51@126.com
?* ? ? ? ?Company: ?
?*
?* =====================================================================================
?*/
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
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->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode))
{
if (strcmp(".", entry->d_name) == 0 ||
strcmp("..", entry->d_name) == 0)
{
continue;
}
printf("%*s%s\n", depth, "", entry->d_name);
printdir(entry->d_name, depth+4);//recurse at new indent level
}
else
{
printf("%*s%s\n", depth, "", entry->d_name);
}
}
chdir("..");
closedir(dp);
}
int main()
{
printf("Directory scan of /home :\n");
printdir("/home/vergil/C/", 0);
printf("done");
}
總結(jié)
- 上一篇: UNIX创建临时文件
- 下一篇: 简单介绍Fedora 8飞信安装及解压