Linux C文件系统作业——6

本文介绍了一个使用C语言编写的程序,该程序能够递归遍历指定目录(如/home),打印所有文件和子目录的名称及节点号,并判断文件类型。通过lstat()、getcwd()等函数,结合<dirent.h>库实现目录和文件的深度遍历。

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

编写程序完成以下功能:

1.递归遍历/home目录,打印出所有文件和子目录名称及节点号。

2.判断文件类型,如果是子目录,继续进行递归遍历,直到遍历完所有子目录为止。

代码如下:

#include<stdio.h>
#include<dirent.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#include<bits/stdio.h>
#include<dirent.h>

char ss[256];

void Judge(char *Buffer)
{
	DIR *dir; 
	struct dirent *dirp; 
	struct stat statbuf;
	char Buf[256];
	strcpy(Buf,Buffer);
	printf("\n\n\nBuffer:%s\n",Buf);
	if(lstat(Buf,&statbuf)<0)
    {         
		perror("lsata:"); 
   	}
	
 	if(S_ISDIR(statbuf.st_mode))
	{         
		dir = opendir(Buf);
        if(dir) 
		{             
			while((dirp = readdir(dir)) != NULL)
			{                 
				if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0)
                continue; 
                printf("\ninode = %ld\n", dirp->d_ino); 
                printf("file name:%s\n",dirp->d_name);
                printf("cwd:	%s\n",getcwd(ss,255));
				if(dirp->d_type == 4)
				{
					strcat(Buf,"/");
					strcat(Buf,dirp->d_name);        
            		Judge(Buf);
				}
            }
            
		}
		else
        {
			perror("opendir error:"); 	  
		}
		closedir(dir); 
	}
	else
	{
		printf("This is not directory\n");
	}
}



int main()
{
	DIR *dir; 
	struct dirent *dirp; 
	struct stat statbuf;
	char Buffer[256];
	printf(".........................................");
	getcwd(Buffer, 255);
    	printf("\nthe current dir is : %s\n",Buffer);

	strcpy(Buffer,"/home/yang/zuoye_2");
	Judge(Buffer);
	printf("...........................................\n");
	return 0;
}

涉及的知识点:

1递归

2文件信息相关函数 :lstat()getcwd()函数

3目录文件库<dirent.h>的相关操作:DIR 结构体 dirent结构体

4string库里部分函数

 

参考过的博客:https://www.cnblogs.com/xudong-bupt/p/3504442.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值