Linux下目录遍历&结构体dirent


在linux下遍历某一目录下内容LINUX下历遍目录的方法一般是这样的
打开目录->读取->关闭目录
相关函数是opendir -> readdir -> closedir,其原型如下:
#include <dirent.h>
DIR *opendir(const char *dirname);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

简单列举一例:

#include<dirent.h>    

  

struct dirent* ent = NULL;
DIR
*pDir;

if( (pDir=opendir("/home/test")) == NULL)
{
printf(
"open dir %s failed\n", pszBaseDir);
return false;
}

while( (ent=readdir(pDir)) != NULL )
{
printf("the ent->d_reclen is%d the ent->d_type is%d the ent->d_name is%s\n", ent->d_reclen, ent->d_type, ent->d_name);

}


closedir(pDir);

其中有一很关键的结构体dirent:

代码
On Linux, the dirent structure is defined as follows: 

struct dirent {
ino_t d_ino;
/* inode number */
off_t d_off;
/* offset to the next dirent */
unsigned
short d_reclen; /* length of this record */
unsigned
char d_type; /* type of file */
char d_name[256]; /* filename */
};

其中inode表示存放的是该文件的结点数目(具体可了解linux下的文件系统),d_off 是文件在目录中的编移,这两个基本很少用。

d_type表示档案类型:

enum
{
    DT_UNKNOWN = 0,
# define DT_UNKNOWN DT_UNKNOWN
    DT_FIFO = 1,
# define DT_FIFO DT_FIFO
    DT_CHR = 2,
# define DT_CHR DT_CHR
    DT_DIR = 4,
# define DT_DIR DT_DIR
    DT_BLK = 6,
# define DT_BLK DT_BLK
    DT_REG = 8,
# define DT_REG DT_REG
    DT_LNK = 10,
# define DT_LNK DT_LNK
    DT_SOCK = 12,
# define DT_SOCK DT_SOCK
    DT_WHT = 14
# define DT_WHT DT_WHT
};

d_reclen认为是纪录的长度,计算方式应该是4(d_ino)+4(d_off)+2(d_reclen)+1(d_type)+1(补齐位)+4N(d_name会自动补齐:1.jpg为8,12.jpg也为8,1234.jpg也为8,12345.jpg则为12);所以一般d_reclen是20和24(其中.和..是16)。

d_name表示文件名,如test.jpg

优质内容筛选与推荐>>
1、SocketServer model_use
2、Java知识-抽象类
3、集合中存储的是对象么
4、2015 - 年终前端笔试题
5、Linux----------开始使用Screen


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn