编程实现LINUX下目录的层层遍历

/*************************************************************************
> File Name: treedir.c
> Author: KrisChou
> Mail:zhoujx0219@163.com
> Created Time: Tue 19 Aug 2014 05:04:50 PM CST
************************************************************************/ #include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h> void print_tree(char* dirname, int spc_cnt); int main(int argc, char* argv[])// ./main dir
{
if(argc == 1)
{
print_tree(".", 0);
}else if(argc == 2)
{
print_tree(argv[1], 0);
}
return 0 ;
} void print_tree(char* dirname, int spc_cnt)
{
DIR* pdir ; //目录指针
struct dirent* pent ; //可以获取目录下子项d_name的结构体指针
struct stat my_stat ; //根据绝对路径,获取文件信息的结构体 char old_path[128]=""; //保存原来的工作路径
getcwd(old_path, 128); pdir = opendir(dirname); //打开目录
if(pdir == NULL)
{
perror("opendir");
exit(1);
} chdir(dirname); //切换到需要遍历的目录 while((pent = readdir(pdir)) != NULL)
{
if(strncmp(pent ->d_name, ".", 1) == 0 || strncmp(pent->d_name,"..", 2) == 0)
{
continue ;
} memset(&my_stat, 0 , sizeof(my_stat));
if(stat(pent ->d_name, &my_stat) == -1)
{
perror("stat");
exit(1);
} if(S_ISDIR(my_stat.st_mode))
{
printf("%*s%s\n",spc_cnt," ",pent ->d_name);
print_tree(pent ->d_name, spc_cnt + 5);
}else
{
printf("%*s%s\n",spc_cnt," ",pent ->d_name);
}
} closedir(pdir);
chdir(old_path); //程序结束切换回原来的目录
}
上一篇:最新Blog


下一篇:Sqlite学习笔记(三)&&WAL性能测试