opendir,打開一個目錄。
函數原型:DIR *opendir(const char *name)
DIR *fopendir(int fd)
DIR是一個結構指針,是一個內部結構,保存所打開的目錄信息。函數出錯返回NULL
?
readdir,讀目錄 ,<dirent.h>
函數原型:struct dirent *readdir(DIR *dirp); //返回一條記錄項(文件或目錄)
int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
struct dirent {ino_t d_ino; //此目錄進入點的inodeff_t d_off; //目錄文件開頭至此目錄進入點的位移signed short int d_reclen; //d_name 的長度,不包含NULLunsigned char d_type; //d_name 所指的文件類型har d_name[256]; //文件名 }
?
?
遞歸獲取文件個數
#include <dirent.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h>int getFileNum(char *root) {//open dirDIR* dir = NULL;dir = opendir(root);if(dir == NULL){perror("opendir");exir(1);}//遍歷當前打開的目錄struct dirent* ptr = NULL;char path[1024] ={0};int total = 0;while(ptr = readdir(dir) != NULL){//過濾. 和 ..if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0){continue;}if(ptr->d_type == DT_DIR){//遞歸 讀目錄sprintf(path, "%s/%s", root, ptr->d_name);total += getFileNum(path);}//如果是普通文件if(ptr->d_type == DT_REG){total++;}}//還需要關閉目錄 closedir(dir);return total; }int main(int argc, char *argv[]) {if(argc < 2){printf("./a.out dir\n");exit(1);}int total = getFileNum(argv[1]);printf("%s has file numbers %d\n", argv[1], total);return 0; }
?