ÔÚ²âÊÔĿ¼²Ù×÷º¯ÊýµÄ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 <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <error.h>
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;
}
ËùÒÔ¾ÍÓÐÁËÒ»¸ö½áÂÛ£¬Óöµ½ÀàËƵÄÎÊÌâµÄʱºò£¬¿ÉÒÔÈ¥¿´¿´Í·ÎļþÊÇÈçºÎ¶¨ÒåÕâ¸ö½á¹¹ÌåµÄ£¬ÄÇôÎÒÃǾͰ´ÕÕÕâ¸ö¶¨ÒåµÄ·½·¨À´´òÓ¡£¨²Ù×÷£©Ïà¹ØµÄÊýÖµ¡£