Linux 下显示目录内容的c语言程序

最近打算学学linux,看了看基础的介绍感觉不明所以,目前在看《Linux程序设计》,看到第三章一个显示目录的程序,感觉C语言和linux简直是天作之合,C语言提供很多底层的函数和一些库函数,可以进行很多方便操作。再和SHELL配合起来对linux编程,确实很爽呀。


记录一下今天的代码:

#include
#include
#include
#include
#include
#include


void printdir(char *dir, int depth);

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");

    return 0;
}

void printdir(char *dir, int depth) // depth表示每一层目录的缩进长度
{
    DIR *dp; // 指向打开的目录
    struct dirent *entry; // dirent结构体的指针,指向读取目录中的每一个条目
    struct stat statbuf; // 存储目录中每个条目的状态信息

    if ((dp = opendir(dir)) == NULL) //判读是否正确打开目录
    {
        fprintf(stderr,"cannot open the 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); //显示目录的名字,注意%*s的意义
            printdir(entry->d_name, depth+4);
        }
        else // 如果不是目录就直接显示该条目名字
        {
            printf("%*s%s/\n", depth, "", entry->d_name);
        }
    }
    chdir(".."); //结束递归
    closedir(dp);
}



你可能感兴趣的:(linux)