Created
March 16, 2019 06:48
-
-
Save hxmwr/8dc1fcfbd90ddae591aaa863935f2d6a to your computer and use it in GitHub Desktop.
C traverse directory with callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/dir.h> | |
#include <dirent.h> | |
int traverse_dir(char *path, int level, int (*callback)(struct dirent *, int)) | |
{ | |
DIR *handle = opendir(path); | |
int path_len; | |
struct dirent *dp; | |
while ((dp = readdir(handle)) != 0) { | |
if (strcmp(".", dp->d_name) == 0 || strcmp("..", dp->d_name) == 0) continue; | |
if (callback(dp, level) == 0) goto LEAVE_FAILED; | |
if (dp->d_type == DT_DIR) { | |
path_len = strlen(path); | |
snprintf(path, 1024, "%s/%s", path, dp->d_name); | |
if (traverse_dir(path, level + 1, callback) == 0) goto LEAVE_FAILED; | |
path[path_len] = '\0'; | |
} | |
} | |
LEAVE_SUCCESS: | |
closedir(handle); | |
return 1; | |
LEAVE_FAILED: | |
closedir(handle); | |
return 0; | |
} | |
int print_dir(struct dirent *dp, int level) | |
{ | |
printf("->%s\n", dp->d_name); | |
return 1; | |
} | |
int main(int argc, char **argv) | |
{ | |
char path[1024] = {0}; | |
strcpy(path, "."); | |
traverse_dir(path, 0, print_dir); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment