【理解】一个利用递归打印对象路径下所有文件的小程序

本文介绍了一段使用C语言实现的目录遍历代码,包括使用`opendir`, `readdir`, `lstat`等函数操作目录,以及如何在递归过程中处理目录和文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<unistd.h>
#include<stdio.h>
#include<dirent.h>
#include<sys/stat.h>
#include<stdlib.h>

void printdir(char *dir, int depth)
{
    DIR *dp;
    struct dirent *entry; //dirent不仅仅指向目录,还指向目录中的具体文件
    struct stat statbuf; //stat,lstat,fstat1 函数都是获取文件:普通文件,目录,管道,socket,字符,块()的属性。函数原型#include <sys/stat.h>
			// lstat函数与stat类似,但是当文件是一个符号连接时,lstat返回该符号连接的有关信息,而不是由该符号连接引用的文件的信息。

    if ((dp=opendir(dir))==NULL){  //opendir来自dirent.h
        
        fprintf(stderr,"cannot open directory: %s\n",dir);
        return;
     }
    
    chdir(dir); //As you use the cd command in the shell to change directory, so a program can use the chdir system call.
    
    while((entry = readdir(dp))!=NULL){
       
	lstat(entry->d_name,&statbuf); //lstat函数用来连接文件描述名,获取文件属性。
					//通过readdir函数读取到的文件名存储在结构体dirent的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); //递归继续往里走,直到走到尽头只有文件而没有目录。depth这货是专门用来占位的

        }   
        else printf("%*s%s\n",depth,"",entry->d_name); //不是目录的话,直接print名字。depth这货是专门用来占位的,对应%*s,使得打印出来的东西有层次。

    }

    chdir("..");
    closedir(dp);    

}



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

最后上个图片子


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

取啥都被占用

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值