专栏中心

EEPW首页 > 专栏 > 【练习】Linux C 读取文件夹下所有文件(包括子文件夹)的文件名

【练习】Linux C 读取文件夹下所有文件(包括子文件夹)的文件名

发布人:电子禅石 时间:2020-04-21 来源:工程师 发布文章

转自:https://www.cnblogs.com/xudong-bupt/p/3504442.html

本文:http://www.cnblogs.com/xudong-bupt/p/3504442.html

Linux C  下面读取文件夹要用到结构体struct dirent,在头#include <dirent.h>中,如下:

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

其中d_type表明该文件的类型:文件(8)、目录(4)、链接文件(10)等。

#include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <dirent.h>
 5 #include <unistd.h>
 6 int readFileList(char *basePath)
 7 {
 8     DIR *dir;
 9     struct dirent *ptr;
10     char base[1000];
11 
12     if ((dir=opendir(basePath)) == NULL)
13     {
14         perror("Open dir error...");
15         exit(1);
16     }
17 
18     while ((ptr=readdir(dir)) != NULL)
19     {
20         if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
21             continue;
22         else if(ptr->d_type == 8)    ///file
23             printf("d_name:%s/%s\n",basePath,ptr->d_name);
24         else if(ptr->d_type == 10)    ///link file
25             printf("d_name:%s/%s\n",basePath,ptr->d_name);
26         else if(ptr->d_type == 4)    ///dir
27         {
28             memset(base,'\0',sizeof(base));
29             strcpy(base,basePath);
30             strcat(base,"/");
31             strcat(base,ptr->d_name);
32             readFileList(base);
33         }
34     }
35     closedir(dir);
36     return 1;
37 }
38 
39 int main(void)
40 {
41     DIR *dir;
42     char basePath[1000];
43 
44     ///get the current absoulte path
45     memset(basePath,'\0',sizeof(basePath));
46     getcwd(basePath, 999);
47     printf("the current dir is : %s\n",basePath);
48 
49     ///get the file list
50     memset(basePath,'\0',sizeof(basePath));
51     strcpy(basePath,"./XL");
52     readFileList(basePath);
53     return 0;
54 }


执行输出 :


专栏文章内容及配图由作者撰写发布,仅供工程师学习之用,如有侵权或者其他违规问题,请联系本站处理。 联系我们

关键词:

相关推荐

人工智能在芯片设计中的潜力与局限

嵌入式系统在商业领域的重要性日益凸显

海光双芯“亮剑”:发布“内生安全”技术,冲刺万亿参数大模型训练

打造自有知识产权的IETM平台

构建以软件为核心的自动化测试系统

TI AM13E230x MCU 赋能边缘 AI 电机控制,破解人形机器人执行器和智能家电关键难题

2010全球电子峰会:MEMS is HOT(下)

视频 2010-05-17

RS-232、RS-422与RS-485标准及应用

资源下载 2007-02-09

RS-232-C详解

源来如此|在上电之前,如何测量 LLC 谐振回路的增益曲线?

测试测量 2026-04-03

2010全球电子峰会:MEMS is HOT(上)

视频 2010-05-17

第四代示波器创新、卓越与价值 (上)

贸泽开售适用于工业、无线电和物联网系统的Qorvo QPA9510功率放大器

RS422RS485技术标准

亿道信息启动Agent One项目:打造端侧AI中枢,开启智能代理新时代

华尔街日报:特斯拉Optimus机器人依赖中国供应链

Quartus II 编程器(Altera)

自动测试设备的校准痛点,埋入式齐纳技术怎么解决?

内存墙越筑越高

网络与存储 2026-04-03
更多 培训课堂
更多 焦点
更多 视频

技术专区