"); //-->
转自: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 }执行输出 :

专栏文章内容及配图由作者撰写发布,仅供工程师学习之用,如有侵权或者其他违规问题,请联系本站处理。 联系我们
相关推荐
人工智能在芯片设计中的潜力与局限
[转帖]学C++人不得不看的好帖!
嵌入式系统在商业领域的重要性日益凸显
ISO122P/124的单电源工作电路
海光双芯“亮剑”:发布“内生安全”技术,冲刺万亿参数大模型训练
2002年中国软件企业十大特征
打造自有知识产权的IETM平台
构建以软件为核心的自动化测试系统
TI AM13E230x MCU 赋能边缘 AI 电机控制,破解人形机器人执行器和智能家电关键难题
2010全球电子峰会:MEMS is HOT(下)
RS-232、RS-422与RS-485标准及应用
检测4~20mA环路仪器放大电路(ISO122P/124、XTR101、RCV420)
RS-232-C详解
源来如此|在上电之前,如何测量 LLC 谐振回路的增益曲线?
2010全球电子峰会:MEMS is HOT(上)
ISO122的低成本三端口、四通道隔离式数据采集系统电路
第四代示波器创新、卓越与价值 (上)
贸泽开售适用于工业、无线电和物联网系统的Qorvo QPA9510功率放大器
今年我国电子信息产品市场呈现五大特点
RS422RS485技术标准
提高电源抑制比(PSR)电路(ISO124)
ISO122P/124的输入侧电源隔离放大电路
QS9000标准
亿道信息启动Agent One项目:打造端侧AI中枢,开启智能代理新时代
华尔街日报:特斯拉Optimus机器人依赖中国供应链
Quartus II 编程器(Altera)
自动测试设备的校准痛点,埋入式齐纳技术怎么解决?
内存墙越筑越高
谁有 bluecat ?
2002年互联网应用10大设计失误