日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

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

發(fā)布時間:2023/12/10 linux 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Linux C 读取文件夹下所有文件(包括子文件夹)的文件名 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本文: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 索引節(jié)點號 */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)等。

?

下面程序,遞歸讀取某文件夾及其子文件夾下所有文件名:

1 #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 }

執(zhí)行輸出 :


總結

以上是生活随笔為你收集整理的Linux C 读取文件夹下所有文件(包括子文件夹)的文件名的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。