【转载】struct dirent 和 DIR结构体 详解

原文地址:https://blog.csdn.net/sin0803/article/details/37539313

1.包含头文件

#include <dirent.h>

2.struct dirent结构

1 struct dirent
2 {
3    long d_ino; /* inode number 索引节点号 */
4    off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
5    unsigned short d_reclen; /* length of this d_name 文件名长 */
6    unsigned char d_type; /* the type of d_name 文件类型 */
7    char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
8 }

3.DIR结构

 1 struct __dirstream
 2 {
 3 void *__fd; /* `struct hurd_fd' pointer for descriptor.   */
 4 char *__data; /* Directory block.   */
 5 int __entry_data; /* Entry number `__data' corresponds to.   */
 6 char *__ptr; /* Current pointer into the block.   */
 7 int __entry_ptr; /* Entry number `__ptr' corresponds to.   */
 8 size_t __allocation; /* Space allocated for the block.   */
 9 size_t __size; /* Total valid data in the block.   */
10 __libc_lock_define (, __lock) /* Mutex lock for this structure.   */
11 };
12 
13 typedef struct __dirstream DIR;

4.例子

 1 #define FILETXTCNT 100 //文件数量
 2 #define FILENAMELEN 64 //文件名称
 3  
 4 //存放要解析的基因文件名称
 5 char g_cFileList[FILETXTCNT][FILENAMELEN]; //最多100个文件,每个文件名64字节
 6  
 7 int GetGeneFile(const char *_pcDir)
 8 {    
 9     int iFileCnt = 0;
10     DIR *dirptr = NULL;
11     struct dirent *dirp;
12     char cFileTmp[64] = {0};
13  
14     if((dirptr = opendir(_pcDir)) == NULL)//打开一个目录
15     {
16         return 0;
17     }
18     while ((dirp = readdir(dirptr)) != NULL)
19     {
20         memset(cFileTmp, 0, 64);
21         if ((0 == strncasecmp(dirp->d_name, ".", 1)) || (0 != strcmp(strchr(dirp->d_name, '.'), ".txt")))//过滤掉这个文件
22         {
23             continue;
24         }
25         
26         sprintf(cFileTmp, "%s/%s", _pcDir, dirp->d_name);
27         strcpy(g_cFileList[iFileCnt], cFileTmp);
28         iFileCnt++;
29     }
30     closedir(dirptr);
31     
32     return iFileCnt;
33 }

猜你喜欢

转载自www.cnblogs.com/hulubaby/p/9382337.html