#include <fcntl.h> //open()函數
#include <unistd.h>
#include <stdio.h>
#include <dirent.h> //提供目錄流操作
#include <string.h>
#include <sys/stat.h> //提供屬性操作函數
#include <sys/types.h> //提供mode_t類型
#include <stdlib.h>
/**
* 該函數的作用是遍歷目錄
* @dir 目錄
* @dePth 子目錄前增加空格的數量
*
*
* eg: /home
* ./xiaoming
* ./Downloads
* ./Desktop
* ./6140
* ./root
*1. opendir("/home") 返回子目錄流 ( DIR* ) ./xiaoming 和 ./root
*2. chdir("/home") 切換到/home目錄
*3. readdir(DIR*) 返回指定目錄的下一級信息( dirent* ) 如 ./Downloads ./Desktop
*4. lstat("/home/xiaoming/Downloads", &statbuf); 獲取指定目錄的屬性
*5. chdir(".."); 回到上一級目錄,對應步驟2
*6. closedir("/home") 關閉目錄
*/
void scanDir(char* dir, int dePth) {
DIR* dp; //定義子目錄流指針
struct dirent* entry;//定義dirent結構體指針保存後續目錄
struct stat statbuf; //定義statbuf結構體保存文件屬性
if ((dp = opendir(dir)) == NULL) { //打開目錄,獲得子目錄流指針,判斷操作是否成功
puts("無法打開該目錄");
return;
}
chdir(dir); //切換到當前目錄去
while ((entry = readdir(dp)) != NULL) { //獲得下一級目錄信息,如果爲結束則循環
lstat(entry->d_name, &statbuf); //獲取下一級成員屬性
if (S_IFDIR & statbuf.st_mode) { //判斷下一級成員是否是目錄
if (strcmp(".", entry->d_name) == 0
|| strcmp("..", entry->d_name) == 0) {
//如果獲得的成員符號是 "." 或者 "..",則跳過本次循環
continue;
}
printf("%*s%s/\n",dePth,"",entry->d_name);
scanDir(entry->d_name,dePth+4); //遞歸,掃描下一級目錄
}else{
printf("%*s%s/\n",dePth,"",entry->d_name); //輸出屬性不是目錄的成員
}
}
chdir(".."); //回到上一級目錄
closedir(dp); //關閉子目錄
}
linux環境下掃描文件
最新推荐文章于 2021-04-29 16:11:22 发布