linux目录操作

来源:互联网 发布:c语言表白源代码 编辑:程序博客网 时间:2024/06/03 19:47
1、打开目录
头文件:
    #include <sys/types.h>
    #include <dirent.h>
①函数原型:
    DIR *opendir (const char *name);
参数一:目录的路径
参数二:DIR指针
功能:打开一个目录
返回值:成功返回一个DIR指针,失败返回NULL

②函数原型:
DIR *fdopendir(int fd);
功能和opendir一样,只不过他打开的是一个描述符。
返回值:成功返回一个DIR指针,失败返回NULL

2、关闭目录
头文件:
    #include <sys/types.h>
    #include <dirent.h>
函数原型:int closedir(DIR *dirp);
参数一:目录的DIR指针
返回值:成功返回0,失败返回-1

3.读取目录操作
struct dirent *readdir(DIR *dirp);
参数一:目录的DIR指针
返回值:目录项结构体
struct dirent
{
         ino_t          d_ino;       /* inode number */I-NODE号
         off_t          d_off;       /* not an offset; see NOTES */偏移位置
         unsigned short d_reclen;    /* length of this record */目录项长度
         unsigned char  d_type;      /* type of file; not supported by all filesystem types */文件类型
         char           d_name[256]; /* filename */文件名字
};
---------------------------------------------------------------------------------------
获取目录下的所有文件名(不包括目录下的目录及其文件)
#include <stdio.h>#include <sys/types.h>#include <dirent.h>#include <error.h>#include <string.h>int main(int argv,char *argc[]){if(argv < 2){perror("plese input ./XX XX\n");}DIR *dir =  opendir(argc[1]);if(dir == NULL){perror("opendir fail\n");return 0;}struct dirent *p = NULL;while(1){p = readdir(dir);if(p == NULL)//要先判断在打印break;printf("%s\n",p->d_name);}closedir(dir);return 0;}


------------------------------------------------------------------------------------
4.删除目录
函数原型:
    int rmdir(const char*pathname);
参数一:目录的名字
返回值:成功返回0,失败返回-1

5.创建目录
头文件:
    #include <unistd.h>
    #include <sys/types.h>
函数原型:
    int mkdit (const char *pathname ,mode_t mode);
参数一:创建的目录的名字
参数二:目录的权限
返回值:成功返回0,失败返回-1

小知识:修改文件权限函数
头文件:
    #include <sys/types.h>
    #include <sys/stat.h>
函数原型:mode_t umask(mode_t mask);

--------------------------------------------------------------------------------------
检索目录下的所有文件,包括子目录的文件:
#include <stdio.h>#include <sys/stat.h>#include <dirent.h>#include <stdlib.h>#include <error.h>void mydir(char *dir,int depth){DIR *dp = opendir(dir);if(dp == NULL){perror("opendir fail:\n");return ;}chdir(dir);//切换到这个目录struct dirent *p;struct stat st;while((p = readdir(dp)) != NULL){stat(p->d_name,&st);//通过文件名获得详细信息if(S_ISDIR(st.st_mode))//如果判断是目录就递归{if(strcmp(p->d_name,".") == 0 || strcmp(p->d_name,"..") == 0)continue;printf("%*s/%s",depth," ",p->d_name);  //%*s类似于%depths,depth是一个整型printf("-----目录-----\n");mydir(p->d_name,depth+4);}else{printf("%*s/%s",depth," ",p->d_name);printf("+++++文件+++++\n");}}chdir("..");//上层目录closedir(dp);//关闭目录return ;}int main(int argv,char *argc[]){if(argv != 2){perror("argv fail:\n");return 0;}mydir(argc[1],0);return 0;}