以下是我写的简单的目录遍历程序,支持递归遍历。 #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #define MAX_PATH_NAME_LEN 4096 void easy_dir_traverse( char *dir_name) { DIR * p_dir; struct dirent *p_dirent; struct stat statbuf; char * p_full_path; unsigned int ui4_len = 0; if((p_dir = opendir(dir_name)) == NULL) { printf("fail to open %s \n",dir_name); printf(" please check if %s is a folder, or check" " if the path is correct \n",dir_name); return; } printf("\n %s traverse start : \n",dir_name); printf("files under %s are : \n",dir_name); while((p_dirent = readdir(p_dir)) != NULL) { if((strcmp(p_dirent->d_name,".") == 0) || (strcmp(p_dirent->d_name,"..") == 0)) { continue; } ui4_len = (strlen(p_dirent->d_name) + strlen(dir_name) + 2 ); if(ui4_len <= MAX_PATH_NAME_LEN) { p_full_path = (char *)malloc(sizeof(char) * ui4_len); if(p_full_path == NULL) { printf(" fail to alloc memory for file full path \n"); return; } else { sprintf(p_full_path,"%s/%s", dir_name,p_dirent->d_name); } if(stat(p_full_path,&statbuf) < 0) { printf(" stat %s error \n",p_full_path); free(p_full_path); p_full_path = NULL; return ; } printf("%s\n",p_dirent->d_name); if(S_ISDIR(statbuf.st_mode)) { easy_dir_traverse(p_full_path); printf("\n"); } free(p_full_path); p_full_path = NULL; } else { printf(" path is too long , dir" " traverse ends in this level \n"); } } closedir(p_dir); printf("\n %s traverse end : \n",dir_name); } int main(int argc, char *argv[]) { if(argc != 2) { printf("invalid arguments : \n"); printf("program_name dir_to_traverse \n"); return -1; } easy_dir_traverse(argv[1]); getchar(); return 0; } |
|
来自: happy123god > 《读书笔记及小结》