linux 目录操作

//打开一个目录
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name); 
参数一:目录的路径  
返回值:成功返回目录指针 
	  失败  NULL
     
//打开一个文件描述符 
DIR *fdopendir(int fd);

//读取一个目录
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
参数一:需要读取的目录指针
返回值:成功   指向目录信息的结构体指针
	  NULL  则是读到末尾或失败
				
//目录信息:			
struct dirent {
	ino_t d_ino; /* Inode number I_NODE节点*/
	off_t d_off; /* Not an offset; see below 目录项偏移量*/
	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]; /* Null-terminated filename 文件名*/
};

//文件类型的判断 
DT_BLK      //This is a block device. 块设备
DT_CHR      //This is a character device. 字符设备
DT_DIR      //This is a directory.目录文件
DT_FIFO     //This is a named pipe (FIFO). 管道文件
DT_LNK      //This is a symbolic link. 链接文件
DT_REG      //This is a regular file.普通文件
DT_SOCK     //This is a UNIX domain socket. 网络通信文件 
DT_UNKNOWN  //The file type could not be determined.  他也不知道什么类型

//关闭一个目录项指针
int closedir(DIR *dirp);   
  
//创建一个目录
#include <sys/stat.h>
int mkdir(const char *path, mode_t mode); 
参数一:目录的名字 
参数二:文件权限 0666  
返回值:成功 返回0  
	  失败 返回-1  

//删除一个目录
int rmdir(const char *path);
参数一:目录的路径 

//修改文件的权限 
mode_t umask(mode_t cmask);
参数一:需要设置的mask的值 
权限的设置公式:(0666 & ~umask & 0777).   0 ->  1111111111111111
在linux系统里面如果要设置文件的权限必须要配套umask一起计算。
注意:
1、在共享目录中不适用,因为windos与linux的文件系统不一致
2、umask设置的是权限“补码”

int chmod(const char *path, mode_t mode);

(文件拥有者)
S_IRWXU   可读可写可执行
S_IRUSR (S_IREAD)  只读
S_IWUSR (S_IWRITE) 只写
S_IXUSR (S_IEXEC)  执行
------------------
(文件的所属组)
S_IRWXG  可读可写可执行
S_IRGRP  只读
S_IWGRP  只写
S_IXGRP  执行
-------------------
(其他用户)
S_IRWXO   可读可写可执行
S_IROTH   只读
S_IWOTH   只写
S_IXOTH   执行
//demo
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>

//读取目录函数
int read_dir(char *dirpath)
{	
	//读取目录
    DIR *fd=opendir(dirpath);
	if(fd == NULL)
	{
		perror("opendir fail\n");
		return -1;
	}
	
	//开始遍历目录
	while(1)
	{
		//读取目录
        struct dirent *p=readdir(fd);
		if(p == NULL)
		{
			break;
		}

		//跳过隐藏文件  
		if(p->d_name[0] == '.')
		{
			continue;
		}

		//判断文件夹的类型 
		if(p->d_type == DT_DIR)  //目录
		{
			//再次调用读取目录函数
			//路径名的拼接  
			char  newpath[1024]={0};
			sprintf(newpath,"%s/%s",dirpath,p->d_name);
			read_dir(newpath);	
		}
		
		if(p->d_type == DT_REG) //普通文件
		{ 
			printf("path=%s/%s\n",dirpath,p->d_name); 			
		}
	}	
	//关闭已经打开的目录
	closedir(fd);
}

int main()
{
	read_dir("/");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值