Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.1 KiB

  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <dirent.h>
  4. #include <stdlib.h>
  5. #include "process_dir.h"
  6. int process_dir_r(filestruct level) {
  7. if (!level.fullname) {
  8. if (level.name) {
  9. level.fullname = level.name;
  10. } else {
  11. level.fullname = ".";
  12. }
  13. }
  14. int errct = 0;
  15. DIR *current = opendir(level.fullname);
  16. if (!current) {
  17. return 1;
  18. }
  19. struct dirent *entry;
  20. while ((entry = readdir(current))) {
  21. if (entry->d_name[0] == '.') {
  22. continue;
  23. }
  24. filestruct next_level = level;
  25. next_level.name = entry->d_name;
  26. if ((asprintf(&next_level.fullname, "%s/%s", level.fullname, entry->d_name) == -1) ||
  27. (next_level.fullname == NULL)) {
  28. return 1;
  29. }
  30. if (entry->d_type == DT_DIR) {
  31. next_level.depth++;
  32. if (level.directory_action) {
  33. level.directory_action(next_level);
  34. }
  35. errct += process_dir_r(next_level);
  36. } else if (entry->d_type == DT_REG && level.file_action) {
  37. level.file_action(next_level);
  38. errct += next_level.error;
  39. }
  40. if (next_level.fullname) {
  41. free(next_level.fullname);
  42. }
  43. }
  44. (void) closedir(current);
  45. return errct;
  46. }