dirent.h解析和ls命令实现
2020-01-13 本文已影响0人
MachinePlay
前段时间美团面试让写非递归遍历文件夹里的所有文件(文件夹中可能有文件夹),当时用了个树层次遍历写了代码,面试官好像不熟悉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;
}
![](https://img.haomeiwen.com/i4064394/1f00eaf4fa3dd09f.png)
读者可以尝试使用非递归方法遍历一个文件夹内所有的文件(提示:队列,树层次遍历)