实现目录相关操作


前言

对目录的操作有很多,本文只实现最常用的创建目录和获取目录下的文件以及获取目录及其所有子目录下的文件


一、逐级创建目录

/*
 * 此程序用于测试MKDIR函数
 * 作者:zhy 时间:2020 1 30
 */

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

//检查目录是否存在,如果不存在则逐级创建子目录
int MKDIR(const char *pathname)
{
	char strPathName[301];

	int ii;
	for(ii=1;ii<strlen(pathname);++ii)
	{
		if(pathname[ii]!= '/' ) continue;

		memset(strPathName,0,sizeof(strPathName));
		strncpy(strPathName,pathname,ii);

		//判断目录是否存在,存在则返回0
		if(access(strPathName,F_OK) == 0) continue;
		if(mkdir(strPathName,0755) !=0) return -1;
	}
	if(mkdir(pathname,0755) !=0) return -1;
	return 0;
}

int main(int argc,char *argv[])
{
	return MKDIR("/home/homeboy/public/aaaa/bbbb/cc");
}


二、获取目录下的文件

/*
 * 此程序用于获取目录中的文件列表
 * 作者:zhy 时间:2020 2 29
 */

#include <stdio.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
	DIR *dir=NULL;
	
	// 用于存放从目录中读取到的文件和目录信息
	struct dirent *strinfo=NULL;

	if((dir=opendir(argv[1]))==0) return -1;

	while(1)
	{
		if((strinfo=readdir(dir))==0) break;
		// 读取一条记录并显示到屏幕
		printf("name = %s , type = %d\n",strinfo->d_name,strinfo->d_type);
	}
	// 关闭目录指针
	closedir(dir);
}

二、获取目录及其所有子目录下的文件

/*
 * 此程序用于列出目录下的所有文件
 * 作者:zhy 时间:2020 2 29
 */

#include <stdio.h>
#include <dirent.h>
#include <string.h>

//获取目录下的所有文件
int ReadDir(const char *strpathname)
{
	DIR *dir=NULL; //定义目录指针

	char strchdpath[256]; //子目录的全路径

	if((dir=opendir(strpathname))==0) return -1;

	struct dirent *strinfo=NULL;  //用于存放从目录读取到的文件和目录信息

	while(1)
	{
		if((strinfo=readdir(dir))==0) break; //读取记录

		if(strncmp(strinfo->d_name,".",1)==0) continue; //跳过以.开头的文件

		if(strinfo->d_type==8)		//如果是文件,显示出来
		printf("name = %s/%s\n",strpathname,strinfo->d_name);

		if(strinfo->d_type==4)		//如果是目录,递归调用ReadDir函数
		{
			sprintf(strchdpath,"%s/%s",strpathname,strinfo->d_name);
			ReadDir(strchdpath);
		}
	}
	closedir(dir);
	return 0;
}

int main(int argc,char *argv[])
{
	//列出目录及子目录下的文件
	return ReadDir(argv[1]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值