posts - 297,  comments - 15,  trackbacks - 0
//功能函数,递归遍历指定目录。
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
输出结果将分页显示。
我们可以此为基础,对之进行有效扩充,以实现更强大实用且通用
的程序。
posted on 2010-01-05 20:21 chatler 阅读(464) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2010年4月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

常用链接

留言簿(10)

随笔分类(307)

随笔档案(297)

algorithm

Books_Free_Online

C++

database

Linux

Linux shell

linux socket

misce

  • cloudward
  • 感觉这个博客还是不错,虽然做的东西和我不大相关,觉得看看还是有好处的

network

OSS

  • Google Android
  • Android is a software stack for mobile devices that includes an operating system, middleware and key applications. This early look at the Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
  • os161 file list

overall

搜索

  •  

最新评论

阅读排行榜

评论排行榜