#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类似)
注意:该函数无法嵌套创建多个目录