遍历目录下的所有文件(Linux C)

上一篇 / 下一篇  2011-11-17 10:39:03 / 个人分类:Linux

/*此脚本遍历输入目录下所有文件*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#define MAX 1024
int get_file_count(char *root)
{
    DIR * dir;
    struct dirent * ptr;
int total = 0;
 char path[MAX];
   
    dir = opendir(root);
   if(dir == NULL){
        perror("fail to open dir");
        exit(1);
    }
    errno = 0;
    while((ptr = readdir(dir)) != NULL){
  if(strcmp(ptr->d_name,".") == 0  || strcmp(ptr->d_name,"..") == 0)
              continue;
          if(ptr->d_type == DT_DIR){       
        if(root[strlen(root)-1] =='/')
           sprintf(path, "%s%s", root, ptr->d_name); 
        else
 sprintf(path, "%s/%s", root, ptr->d_name);
//   printf("d_name :  %s\n",path);
             total += get_file_count(path);
          }
          if(ptr->d_type == DT_REG)
{
      if(root[strlen(root)-1] =='/')
           sprintf(path, "%s%s", root, ptr->d_name);
        else
        sprintf(path, "%s/%s", root, ptr->d_name);
   printf("d_name :  %s\n",path);
      total++;   
}
    }
    if(errno != 0){
       perror("fail to read dir");
        exit(1);
    }
   
    closedir(dir);
  return total;
}
int main(int argc, char * argv[])
{
    int total;
   
    if(argc != 2){
        printf("wrong usage/n");
        exit(1);
    }
    total = get_file_count(argv[1]);
//  printf("%s has %d files\n", argv[1], total);
    return 0;
}

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-01  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 3993
  • 日志数: 6
  • 建立时间: 2010-07-03
  • 更新时间: 2011-11-17

RSS订阅

Open Toolbar