micro-utils/libmu/recurse.c

50 lines
1.1 KiB
C
Raw Normal View History

2024-07-01 10:23:00 +00:00
#include <stdio.h>
#include <dirent.h>
2024-07-09 19:33:45 +00:00
#include <stdlib.h>
2024-07-01 10:23:00 +00:00
#include <string.h>
#include "make_path.h"
#include "get_stat.h"
2024-07-09 19:33:45 +00:00
int mu_recurse(const char *restrict prog_name, int link_flag, const char *restrict path, void *restrict arg, int (*file_act)(const char *path, void *p), int (*dir_act)(const char *path, void *p)) {
2024-07-01 10:23:00 +00:00
struct stat sb;
if (mu_get_stats(prog_name, link_flag, path, &sb))
return 1;
if (!S_ISDIR(sb.st_mode) || S_ISLNK(sb.st_mode)) {
if (file_act != NULL)
return file_act(path, arg);
}
DIR *dir = opendir(path);
if (dir == NULL) {
if (prog_name != NULL)
fprintf(stderr, "%s: %s: Can`t open directory\n", prog_name, path);
return 1;
}
int ret = 0;
struct dirent *ep;
while ((ep = readdir(dir)) != NULL) {
if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
continue;
char *full_path = mu_make_path(prog_name, path, ep->d_name);
if (full_path == NULL)
continue;
if (mu_recurse(prog_name, link_flag, full_path, arg, file_act, dir_act))
ret = 1;
free(full_path);
}
closedir(dir);
if (dir_act != NULL)
if (dir_act(path, arg))
ret = 1;
return ret;
}