dirent.h解析和ls命令实现

前段时间美团面试让写非递归遍历文件夹里的所有文件(文件夹中可能有文件夹),当时用了个树层次遍历写了代码,面试官好像不熟悉C的库,当时也没解释,在这里复习一下C标准库,以后面试面试官不熟悉就直接看博客把

dirent

dirent.h是用于目录操作的头文件,linux 默认在/usr/include目录下(会自动包含其他文件),常见的方法如下:

The <dirent.h> header shall define the following type:

DIR //结构体
A type representing a directory stream.

It shall also define the structure dirent which shall include the following members:

ino_t  d_ino       File serial number. //inode号
char   d_name[]    Name of entry.  //文件名

The type **ino_t** shall be defined as described in [*<sys/types.h>*]
The character array d_name is of unspecified size, but the number of bytes preceding the terminating null byte shall not exceed {NAME_MAX}.

The following shall be declared as functions and may also be defined as macros. Function prototypes shall be provided.

int            closedir(DIR *); //关闭句柄
DIR           *opendir(const char *); //打开名为xxx的文件,返回句柄
struct dirent *readdir(DIR *); //读取文件 返回dirent结构体

void           rewinddir(DIR *);
void           seekdir(DIR *, long);
long           telldir(DIR *); //返回当前指针的位置,表示第几个元素

不同平台下的dirent 结构体各异,如mac:

struct dirent {
        ino_t d_ino;                    /* file number of entry */
        __uint16_t d_reclen;            /* length of this record */
        __uint8_t  d_type;              /* file type, see below */
        __uint8_t  d_namlen;            /* length of string in d_name */
        char d_name[__DARWIN_MAXNAMLEN + 1];    /* name must be no longer than this */
};

这里我们写一个简单的ls命令实现
all.h即apue.h

#include "../all.h"
#include "dirent.h"

int main(int argc, char * argv[]) {
    DIR * dp;
    dirent * dirp;
   
    printf("this is a simple ls \n");
    if (argc != 2) {
        printf("argument not enough\n");
        exit(-1);
    }

    if ((dp = opendir(argv[1])) == NULL) {
        printf("can't open file %s. \n");
        exit(-1);
    }
    
    while((dirp = readdir(dp)) != NULL) {
        printf("filename : %s    ino : %lld\n",dirp->d_name, dirp->d_ino);
    }

    closedir(dp);

    return 0;


}
4064394-1f00eaf4fa3dd09f.png
效果

读者可以尝试使用非递归方法遍历一个文件夹内所有的文件(提示:队列,树层次遍历)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值