70 lines
1.8 KiB
C
70 lines
1.8 KiB
C
#include <dirent.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <sys/stat.h>
|
|
#include <unistd.h>
|
|
|
|
void walk_dir(const char *path, int follow_symlinks, int ignore_hidden) {
|
|
DIR *dir = opendir(path);
|
|
if (!dir) {
|
|
perror(path);
|
|
return;
|
|
}
|
|
|
|
struct dirent *entry;
|
|
while ((entry = readdir(dir)) != NULL) {
|
|
if (strncmp(entry->d_name, ".", 1) == 0)
|
|
continue;
|
|
|
|
if (strncmp(entry->d_name, "..", 2) == 0)
|
|
continue;
|
|
|
|
// Skip hidden files if requested
|
|
if (ignore_hidden && entry->d_name[0] == '.')
|
|
continue;
|
|
|
|
char fullpath[4096];
|
|
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
|
|
|
|
struct stat st;
|
|
int ret;
|
|
if (follow_symlinks)
|
|
ret = stat(fullpath, &st);
|
|
else
|
|
ret = lstat(fullpath, &st);
|
|
|
|
if (ret != 0) {
|
|
/* Permission denied ends up here */
|
|
perror(fullpath);
|
|
continue;
|
|
}
|
|
|
|
/* There are a bunch of macros in <sys/stat.h> like S_ISDIR for checking */
|
|
printf("FILE: %s\n", fullpath);
|
|
if (S_ISDIR(st.st_mode)) {
|
|
walk_dir(fullpath, follow_symlinks, ignore_hidden);
|
|
}
|
|
}
|
|
|
|
closedir(dir);
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
if (argc < 2) {
|
|
fprintf(stderr, "Usage: %s <dir> [--follow-symlinks] [--ignore-hidden]\n", argv[0]);
|
|
return 1;
|
|
}
|
|
|
|
int follow_symlinks = 0;
|
|
int ignore_hidden = 0;
|
|
|
|
for (int i = 2; i < argc; i++) {
|
|
if (strcmp(argv[i], "--follow-symlinks") == 0)
|
|
follow_symlinks = 1;
|
|
if (strcmp(argv[i], "--ignore-hidden") == 0)
|
|
ignore_hidden = 1;
|
|
}
|
|
|
|
walk_dir(argv[1], follow_symlinks, ignore_hidden);
|
|
return 0;
|
|
}
|