在测试目录操作函数的readdir()函数时,要传递一个struct dirent的结构体去接收读取到的文件的信息。这个结构体在系统帮助手册如下 man 3 readdir: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; not supported by all file system types 文件系统支持的文件类型 */char d_name[256]; /* filename 文件名 */};关于这个结构体的成员,除了d_type外,其他成员问题不大,如 d_ino, d_off,d_reclen都是用整型数据来表示数值,d_name是用字符串来表示文件名,而d_type用一个 unsigned char 类型表示文件类型,那么这个文件类型是什么?所以决定打印出来,使用"%c"的格式控制符,结果是 “d_type= ”,是一些垃圾数值,那么问题在哪呢?于是去看来一下这个结构体的定义源码,发现d_type定义如下:
#ifdef __USE_BSD
/* File types for `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"的格式控制符,结果就打印了相对应的数值。
#include
#include
#include
#include
int main()
{
//打开目录
DIR * pdir = opendir(".");
if(pdir == NULL)
{
perror("opendir");
return -1;
}
//定义一个目录内文件的信息的结构体
struct dirent * pdirent;
//读取目录内容的信息
while((pdirent = readdir(pdir)) != NULL)
{
printf("d_ino= %d\n",pdirent->d_ino);
printf("d_off= %d\n",pdirent->d_off);
printf("d_reclen= %d\n",pdirent->d_reclen);
printf("d_type= %c\n",pdirent->d_type);
printf("d_name= %s\n",pdirent->d_name);
}
int ret = closedir(pdir);
if(ret == -1)
{
perror("closedir");
return -1;
}
return 0;
}
所以就有了一个结论,遇到类似的问题的时候,可以去看看头文件是如何定义这个结构体的,那么我们就按照这个定义的方法来打印(操作)相关的数值。