Linux下遞迴遍歷檔案和資料夾
阿新 • • 發佈:2018-12-31
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/stat.h> #include<string.h> #include<fcntl.h> #include<dirent.h> //利用深度優先遍歷實現檔案檢索 void dfs(const char *filedir) { struct stat dirstat; if(stat(filedir,&dirstat)==-1) { printf("cant access to %s",filedir); exit(1); } if(dirstat.st_mode & S_IFDIR) { struct dirent *entry; DIR * dir; dir = opendir(filedir); printf("%s\n",filedir); while((entry = readdir(dir))!=NULL) { if(!strcmp(entry->d_name,".")||!strcmp(entry->d_name,".."))continue; char src[255]; strcpy(src,filedir); strcat(src,"/"); chdir(strcat(src,entry->d_name)); dfs(src); chdir(filedir); } } else { printf("--%s\n",filedir); } } int main(int argc,char *args[]) { if(argc!=2) { printf("tree filedir"); } dfs(args[1]); return 0; }
在Linux下檢索檔案跟windows下一樣,只不過檔案結構稍有不同,需要了解linux下的檔案儲存方式
struct stat 是一個指向檔案指標的結構體。檢視stat的資訊可以通過man 2 struct stat檢視 如下
struct stat { /* when _DARWIN_FEATURE_64_BIT_INODE is NOT defined */ dev_t st_dev; /* device inode resides on */ ino_t st_ino; /* inode's number */ mode_t st_mode; /* inode protection mode */ nlink_t st_nlink; /* number of hard links to the file */ uid_t st_uid; /* user-id of owner */ gid_t st_gid; /* group-id of owner */ dev_t st_rdev; /* device type, for special file inode */ struct timespec st_atimespec; /* time of last access */ struct timespec st_mtimespec; /* time of last data modification */ struct timespec st_ctimespec; /* time of last file status change */ off_t st_size; /* file size, in bytes */ quad_t st_blocks; /* blocks allocated for file */ u_long st_blksize;/* optimal file sys I/O ops blocksize */ u_long st_flags; /* user defined flags for file */ u_long st_gen; /* file generation number */ };
我們可以通過獲得stat的一些屬性知道inode 號和記錄屬性等,inode記錄檔案位置等資訊,從而找到磁碟中的資料。在這裡我們用stat的屬性區分檔案還是資料夾,然後利用opendir獲取檔案目錄,readdir依此讀取目錄中檔案。如有疑問或者錯誤歡迎大家留言討論,原創 轉載請說明出處