嵌套读取目录

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


//嵌套读取文件信息
int read_dir(char *dirp)
{
	char buf[100];
	getcwd(buf,sizeof(buf));//当前的绝对路径
	if(0==access(dirp,F_OK))//文件存在?
	{
		struct stat st;
		stat(dirp,&st);
		if((st.st_mode&S_IFMT)==S_IFREG)//普通文件
		{
			printf("%s/%s\n",buf,dirp);
		}
		if((st.st_mode&S_IFMT)==S_IFDIR)//目录
		{
			printf("%s/%s/\n",buf,dirp);
			//打开目录
			DIR *dp=opendir(dirp);
			if(NULL==dp)
			{
				perror("打开目录失败\n");
				return -1;
			}
			//读取目录
			struct dirent *fp;
			while(NULL!=(fp=readdir(dp)))
			{	//跳过'.'和'..'
				if((strcmp(fp->d_name,".")==0)||(strcmp(fp->d_name,"..")==0))
					continue;
				if(fp->d_type==DT_DIR)//是目录类型,递归读取目录
				{
					chdir(dirp);//进入目录
					read_dir(fp->d_name);//读目录
				}
				else
					printf("%s/%s\n",buf,fp->d_name);
			}
			closedir(dp);//关闭目录
		}
	}
	else
		printf("文件不存在\n");
	
	return 0;
}


int main(int argc,char **argv)
{
	read_dir(argv[1]);
	
	return 0;
}

 

 

(1)打开目录
    #include <dirent.h>
    DIR *opendir(const char *name);
    返回值:成功返回DIR指针,存放了当前目录的属性信息
    参数: name --》目录的路径名
    
(2)读取目录内容(重点)
    struct dirent *readdir(DIR *dirp);
    返回值: struct dirent
    {
        unsigned char  d_type;      //保存目录中某个目录项的文件类型  
                        DT_BLK      块设备
                        DT_CHR      字符设备
                        DT_DIR      目录
                        DT_FIFO     管道
                        DT_LNK      软链接
                        DT_REG      普通文件
                        DT_SOCK     套接字
        char  d_name[256];  //当前读取到的目录项文件名字
    }
    参数:dirp --》你刚才使用opendir打开的那个目录
    
(3)关闭目录
    int closedir(DIR *dirp);
    
(4)新建目录
    int mkdir(const char *pathname, mode_t mode);
    参数:pathname --》新建的目录路径
    mode --》目录的权限0777(收到umask的影响,计算方法跟open类似)
    注意:该函数无法嵌套创建多个目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值