前言
对目录的操作有很多,本文只实现最常用的创建目录和获取目录下的文件以及获取目录及其所有子目录下的文件
一、逐级创建目录
/*
* 此程序用于测试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]);
}