- 實驗環境linux mint 開發平台 Qt5.11
- 總體思想,linux C的文件目錄相關函數有 mkdir rmdir opendir readdir
- 文件目錄指針類型 DIR*
- dirent代表系統文件目錄相關的結構體,其中屬性d_type文件類型 d_name文件名或目錄名DT_DIR代表文件目錄,DT_REG代表普通文件
#include <stdio.h> #include<stdlib.h> #include<unistd.h> #include<dirent.h> #include<sys/types.h> int getdir(char * pathname) { DIR* path=NULL; path=opendir(pathname); if(path==NULL) { perror("failed"); exit(1); } struct dirent* ptr; //目錄結構體---屬性:目錄類型 d_type, 目錄名稱d_name char buf[1024]={0}; while((ptr=readdir(path))!=NULL) { if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0) { continue; } //如果是目錄 if(ptr->d_type==DT_DIR) { sprintf(buf,"%s/%s",pathname,ptr->d_name); printf("目錄:%s\n",buf); getdir(buf); } if(ptr->d_type==DT_REG) { sprintf(buf,"%s/%s",pathname,ptr->d_name);//把pathname和文件名拼接后放進緩沖字符數組 printf("文件:%s\n",buf); } } return 0; } int main() { getdir("/home/cpc/Pictures"); return 0; }
輸出結果: