码迷,mamicode.com
首页 > 数据库 > 详细

C语言遍历文件和目录——————【Badboy】

时间:2014-08-20 09:20:06      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:c   遍历   

[cpp]

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #define MAX_PATH_LENGTH 512

  #define MAX_FILE_EXTENSION 9

  unsigned long visit_dirs = 0;

  unsigned long visit_files = 0;

  void listdir(char *path){

  DIR *ptr_dir;

  struct dirent *dir_entry;

  int i = 0;

  char *child_path;

  char *file_path;

  child_path = (char*)malloc(sizeof(char)*MAX_PATH_LENGTH);

  if(child_path == NULL){

  printf("allocate memory for path failed.\n");

  return;

  }

  memset(child_path, 0, sizeof(char)*MAX_PATH_LENGTH);

  file_path = (char*)malloc(sizeof(char)*MAX_PATH_LENGTH);

  if(file_path == NULL){

  printf("allocate memory for file path failed.\n");

  free(child_path);

  child_path = NULL;

  return;

  }

  memset(file_path, 0, sizeof(char)*MAX_PATH_LENGTH);

  ptr_dir = opendir(path);

  while((dir_entry = readdir(ptr_dir)) != NULL){

  if(dir_entry->d_type & DT_DIR){

  if(strcmp(dir_entry->d_name,".") == 0 ||

  strcmp(dir_entry->d_name,"..") == 0){

  continue;

  }

  sprintf(child_path, "%s/%s", path, dir_entry->d_name);

  printf("[DIR]%s\n", child_path);

  visit_dirs++;

  listdir(child_path);

  }

  if(dir_entry->d_type & DT_REG){

  sprintf(file_path, "%s/%s", path, dir_entry->d_name);

  printf("[FILE]%s\n", file_path);

  visit_files++;

  }

  }

  free(child_path);

  child_path = NULL;

  free(file_path);

  file_path = NULL;

  }

  int main(int argc, char* argv[]){

  if(argc == 2){

  listdir(argv[1]);

  printf("Total DIR: %ld, Total FILE: %ld\n", visit_dirs, visit_files);

  }else{

  printf("Usage: listdir

\n");

  return;

  }

  return 0;

  }

C语言遍历文件和目录——————【Badboy】,布布扣,bubuko.com

C语言遍历文件和目录——————【Badboy】

标签:c   遍历   

原文地址:http://blog.csdn.net/qq_19522245/article/details/38701321

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!