linux笔记—Linux文件夹操作
linux下文件夹相关操作
切换到文件夹路径下
调用 chdir 即可
1
chdir("/info");
打开文件夹
源码,打开文件夹返回对应文件夹的DIR结构体
1
2
3
4
5DIR *dir;
dir = opendir(pcDirName);
if (NULL == dir){
continue ;
}DIR结构体
1
2
3
4
5
6
7
8
9
10
11
12struct __dirstream
{
void *__fd;
char *__data;
int __entry_data;
char *__ptr;
int __entry_ptr;
size_t __allocation;
size_t __size;
__libc_lock_define (, __lock)
};
typedef struct __dirstream DIR;保存文件夹相关内容,无需深究
源码,遍历文件
1
2
3
4
5
6
7
8
9
10struct direct *ent;
while (NULL != (ent = readdir(dir))){
/*如果 指向 . ..*/
if (0 == strcmp(ent->d_name, ".") \
|| 0 == strcmp(ent->d_name, "..") \
|| 4 == ent->d_type){
continue;
}
/*遍历*/
}dirent结构体
1
2
3
4
5
6
7
8struct dirent
{
long d_ino; /* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen; /* length of this d_name 文件名长 */
unsigned char d_type; /* the type of d_name 文件类型 */
char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
}dirent指向目录和目录中某个具体文件,但还是桥梁作用,访问文件具体内容还需要通过d_name找到stat结构体支援.
源码,获取stat结构体
1
2stat f_stat;
sdwRet = stat(ent->d_name, &f_stat);stat结构体是指向文件的结构体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15struct stat {
mode_t st_mode; //文件访问权限
ino_t st_ino; //索引节点号
dev_t st_dev; //文件使用的设备号
dev_t st_rdev; //设备文件的设备号
nlink_t st_nlink; //文件的硬连接数
uid_t st_uid; //所有者用户识别号
gid_t st_gid; //组识别号
off_t st_size; //以字节为单位的文件容量
time_t st_atime; //最后一次访问该文件的时间
time_t st_mtime; //最后一次修改该文件的时间
time_t st_ctime; //最后一次改变该文件状态的时间
blksize_t st_blksize; //包含该文件的磁盘块的大小
blkcnt_t st_blocks; //该文件所占的磁盘块
};之后愉快访问吧
相关文章