DIR * opendir(const char * name)   打开指定目录

struct dirent * readdir(DIR * dir)     返回dir目录的下个目录进入点

int lstat(const char * file_name,struct stat * buf)  取得文件的文件状态


/*
 * printdir.c
 *
 *  Created on: Jul 21, 2013
 *      Author: yao
 */
#include 
#include 
#include 
#include 
#include 
#include 
/* 打印当前目录函数 */
void printdir(char * dir,int depth)
{
 /* 定义变量 */
   DIR * dp;
   struct dirent * entry;
   struct stat statbuf;
 /* 如果路径无效,输出错误信息并退出 */
   if((dp=opendir(dir))==NULL)
   {
      fprintf(stderr,"cannot open directory:%s\n",dir);
      return ;
   }
   chdir(dir);    //改变当前目录
  /* 循环读取目录下的子目录及文件 */
   while((entry=readdir(dp))!=NULL)
   {
    lstat(entry->d_name,&statbuf);   //获取该目录或文件的文件状态信息
  /* 根据S_ISDIR这个宏定义判断是否是目录 */
    if(S_ISDIR(statbuf.st_mode))
    {
      /* 如果是.或..,跳过这次循环 */
        if(strcmp(".",entry->d_name)==0 || strcmp("..",entry->d_name)==0 )
        {
            continue;
        }
     /* 这里注意%*s格式输出,*表示输出的宽度 */
        printf("%*s%s/\n",depth,"",entry->d_name);
     /* 继续遍历子目录,重复上述过程 */
        printdir(entry->d_name,depth+4);
    }
    else {
        printf("%*s%s\n",depth,"",entry->d_name);
    }
   }
    chdir("..");     //退到上一级目录
    closedir(dp);    //关闭目录指针
}
int main() {
    printf("Directory scan of /home:\n");
    /* 要查找的路径 */
    printdir("/home/lds",0);
    return 0;
}

具体的函数使用请查阅Linux C常用函数.pdf



注:这里只能对/home/lds目录进行查找,现在对代码进行稍稍修改,变成手动输入要查找的目录。

只需修改下main函数即可:

int main(int argc, char **argv)
{
    char * lookupdir=".";    //定义要查找的目录
    if(argc>=2)
    {
       lookupdir=argv[1];   //赋值
    }
                                     
    /*打印当前查找的目录*/ 
    printf("Directory scan of %s:\n",lookupdir);
    /* 调用printdir函数 */
    printdir(lookupdir,0);
    return 0;
}


运行:./printdir /var/log | less


输出内容可分页查找,挺方便的!