#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;
}
标签:txt,name,递归,int,st,char,查找,include,ptr
From: https://www.cnblogs.com/hacker-dvd/p/17754579.html