在使用readdir函数的时候,遇到一个问题–不管是文件还是目录d_type的值都是0(DT_UNKNOWN)
`#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main()
{
DIR *dirp;
struct dirent *dp;
dirp = opendir(“gg/”);
while ( (dp = readdir(dirp) ) != NULL) {
if (strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name, ".") == 0) {
continue;
}
printf("dp->d_name %s \n ", dp->d_name);
printf("dp->d_type: %d\n", dp->d_type);
}
}`
查看了一下man手册readdir函数中对dirent 结构体的定义,和对d_type中的描述中指出d_type不被所有的文件系统支持,对不支持的文件系统d_type会返回DT_UNKNOWN,我使用的文件系统是xfs。所以d_type返回0好像是正常的。
struct dirent {
ino_t d_ino; /* Inode number /
off_t d_off; / Not an offset; see below /
unsigned short d_reclen; / Length of this record /
unsigned char d_type; / Type of file; not supported
by all filesystem types /
char d_name[256]; / Null-terminated filename */
};
Currently, only some filesystems (among them: Btrfs, ext2,
ext3, and ext4) have full support for returning the file
type in d_type. All applications must properly handle a
return of DT_UNKNOWN.
但是我在另一台机器的xfs文件系统的目录下运行同样的代码却可以得到正确的d_type类型。
google了一下,结果是这样的:
As the readdir(3) man page points out, not all filesystems return real info in the d_type field (typically because it would take an extra disk seek to read the inode, as is the case for XFS if you didn’t use mkfs.xfs -n ftype=1 (implied by -m crc=1 which is not yet the default). Filesystems that always set DT_UNKNOWN are common in real life, and not something that you can ignore. XFS is not the only example.
说是ftype是原因,用xfs_info命令查了两台机器运行代码的目录,果然一个ftype是0,一个是1,ftype是1的机器可以正确输出d_type的值