函数介绍的相关文章->关于目录操作相关函数介绍
readdir()
遍历当前目录
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[])
{
char type_buf[512];
DIR *dirp;
struct dirent *entry;
memset(type_buf,0,sizeof(type_buf));
//打开目录
if((dirp=opendir(argv[1])) == NULL);
{
printf("open dir fail\n");
return -1;
}
while(entry == readdir(dirp))
{
//如果是目录文件
if(entry->d_type & DT_DIR)
{
//排除linux的.和..两个文件
if(strcmp(entry->d_name,".")==0 || strcmp(entry->d_name,"..")==0)
continue;
sprintf(type_buf,"%s%s","dir-->",entry->d_name);
printf("%s\n",type_buf);
}
//如果是普通文件
else if(entry->d_type & DT_REG)
{
sprintf(type_buf,"%s%s","nor-->",entry->d_name);
printf("%s\n",type_buf);
}
}
closedir(dirp);
return 0;
}
说明:通过readdir()
函数可以打开目录下的一个文件并返回一个struct dirent
结构体,通过不断调用readdir()
就能将目录下的所有文件都能取到。但是,假如我们打开了A目录,A目录下面有一个B目录,并且B目录里面也有文件的时候,这个时候readdir将无法读取到B目录里面的文件。
各级目录及目录下面的文件是按照树形结构来管理的,而且是多叉树结构,如图:
2. 前序遍历方式遍历目录所有结点
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#define MAX_PATH 512 //定义了缓冲区的大小
void dir_order(char *pathname)
{
DIR *dfd;
char name[MAX_PATH]; //这里是定义了一个缓冲区
struct dirent *dp;
if ((dfd = opendir(pathname)) == NULL)
{
printf("dir_order: can't open %s\n %s", pathname,strerror(errno));
return;
}
while ((dp = readdir(dfd)) != NULL)
{
if (strncmp(dp->d_name, ".", 1) == 0)
continue;
if (strlen(pathname) + strlen(dp->d_name) + 2 > sizeof(name)) //这里+2只是为了给他预留多一点点空间,不加也可以
{
printf("dir_order: name %s %s too long\n", pathname, dp->d_name);
} else
{
memset(name, 0, sizeof(name)); //把缓冲区清零
//这里的sprintf是将我们想要打印的内容,按照我们想要的格式打印出来,并且存到name里面
//第二个参数%s/%s就是我们想要的格式,两个的内容分别是pathname和dp->dname
sprintf(name, "%s/%s", pathname, dp->d_name);
print_file_info(name);
}
}
closedir(dfd);
}
void print_file_info(char *pathname)
{
//获取节点信息
struct stat filestat;
if (stat(pathname, &filestat) == -1)
{
printf("cannot access the file %s", pathname);
return;
}
//打印节点信息
printf("%s %8ld\n", pathname, filestat.st_size);
//如果是目录,递归调用
if ((filestat.st_mode & S_IFMT) == S_IFDIR)
{
dir_order(pathname);
}
}
main函数
int main(int argc, char *argv[])
{
//如果没有传参,遍历当前目录
if (argc == 1)
{
dir_order(".");
}
//否则,遍历指定目录
else
{
dir_order(argv[1]);
}
return 0;
}