linux学习:目录检索

目录

目录

api

例子 


目录

Linux 中的目录并不是一种容器,而仅仅是一个文件索引表

Linux 中目录就是一组由文件名和索引号组成的索引表,目录下的文件的真正内容存储 在分区中的数据域区域。目录中索引表的每一项被称为“目录项”,里面至少存放了一个文 件的名字(不含路径部分)和索引号(分区唯一),当我们访问某一个文件的时候,就是根 据其所在的目录的索引表中的名字,找到其索引号,然后在分区的 i-node 节点域中查找到 对应的文件 i 节点的。

api

操作目录跟标准 IO 函数操 作文件类似,也是先获得“目录指针”,然后读取一个个的“目录项”

该目录结构体为

struct dirent
{
    ino_t d_ino; // 文件索引号
    off_t d_off; // 目录项偏移量
    unsigned short d_reclen; // 该目录项大小
    unsigned char d_type; // 文件类型
    char d_name[256]; // 文件名
};

例子 

获取目录指针,并打印该目录下所有文件的名字

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdbool.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <strings.h>
7 #include <errno.h>
8
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <fcntl.h>
12 #include <dirent.h>
13
14 int main(int argc, char **argv)
15 {
16     if(argc != 2)
17     {
18         printf("Usage: %s <dir>\n", argv[0]);
19         exit(1);
20     }
21
22     DIR *dp = opendir(argv[1]); // 获取指定目录指针
23
24     struct dirent *ep = NULL;
25     while(1)
26     {
27         ep = readdir(dp); // 读取目录项指针
28         if(ep == NULL)
29             break;
30
31         printf("%s\n", ep->d_name); // 打印文件名
32     }
33
34
35     return 0;
36 }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值