Appearance
dirent
在
getdents()的man手册中有 dirent 结构体的解释
c
struct linux_dirent {
unsigned long d_ino; /* Inode number */
unsigned long d_off; /* Offset to next linux_dirent */
unsigned short d_reclen; /* Length of this linux_dirent */
char d_name[]; /* Filename (null-terminated) */
/* length is actually (d_reclen - 2 -
offsetof(struct linux_dirent, d_name)) */
char pad; // Zero padding byte
char d_type; // File type (only since Linux
// 2.6.4); offset is (d_reclen - 1)
}d_type : Linux文件文件类型,这是一个枚举结构的数据,文件类型对应的编号可以查看源码中的编号 glibc/dirent.h。
c
/* File types for `d_type'. */
enum
{
DT_UNKNOWN = 0,
DT_FIFO = 1, // 管道, p
DT_CHR = 2, // 字符设备文件, c
DT_DIR = 4, // 目录, d
DT_BLK = 6, // 块设备文件, b
DT_REG = 8, // 普通文件, -
DT_LNK = 10, // 链接, l
DT_SOCK = 12, // 套接字, s
DT_WHT = 14 // stackoverflow.com/questions/13132667
};d_name: 文件名
opendir
c
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
DIR *fdopendir(int fd);closedir
c
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);readdir
c
#include <dirent.h>
struct dirent *readdir(DIR *dirp);示例代码
列出 root 下的所有文件(不包括隐藏文件)
c
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
int
main(int argc, char const* argv[])
{
DIR* dp;
struct dirent* dt;
dp = opendir("/");
if (NULL == dp) {
perror("opendir()");
return -1;
}
while (1) {
dt = readdir(dp);
if (dt == NULL)
break;
if (dt->d_name[0] != 46)
printf("%s\n", dt->d_name);
}
if (closedir(dp) < 0) {
perror("close()");
return -1;
}
return 0;
}