递归查找目录下的所有txt文件

发布时间 2023-10-10 14:24:33作者: hacker_dvd
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int getTxtNum(const char* path) {
  // 打开目录
  DIR* dir = opendir(path);
  if (dir == NULL) {
    perror("opendir");
    return 0;
  }
  
  struct dirent* ptr = NULL;
  int count = 0;
  struct stat st;
  while ((ptr = readdir(dir)) != NULL) {
    // 遍历到 . 和 .. 项跳过
    if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
      continue;
    }

    char fullPath[1024];
    // 注意这里必须使用完整路径!不能直接使用ptr->d_name,否则会找不到文件
    snprintf(fullPath, sizeof(fullPath), "%s/%s", path, ptr->d_name);
    int flag = stat(fullPath, &st);
    if (flag) {
      printf("%s\n", fullPath);
      perror("read error");
      return 0;
    }
    // 读取到一个目录项
    if (S_ISDIR(st.st_mode)) {
      char newPath[1024];
      snprintf(newPath, sizeof(newPath), "%s/%s", path, ptr->d_name);
      count += getTxtNum(newPath);
    } else if (S_ISREG(st.st_mode)) {  // 普通文件
      char* p = strstr(ptr->d_name, ".txt");
      if(p != NULL && *(p+4) == '\0') {
        count++;
        printf("%s/%s\n", path, ptr->d_name);
      }
    }
  }
  closedir(dir);
  return count;
}
int main(int argc, char* argv[]) {
  if (argc != 2) {
    fprintf(stderr, "please input a directory!\n");
    return -1;
  }

  int num = getTxtNum(argv[1]);
  printf("the number of txt is %d\n", num);

  return 0;
}