Created
October 18, 2024 11:21
-
-
Save skull-squadron/33d3f4c932ecc06936c991ea78bbfbac to your computer and use it in GitHub Desktop.
count files (works on macOS and Linux)
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 <dirent.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#ifdef __APPLE__ | |
#include <sys/syslimits.h> | |
#endif | |
#include <sys/types.h> | |
int count(char *path, size_t n) { | |
int r = 0; | |
size_t name_len; | |
struct dirent *f; | |
DIR *d = opendir(path); | |
if (!d) { | |
perror(path); | |
exit(EXIT_FAILURE); | |
} | |
while ((f = readdir(d))) { | |
if (f->d_name[0] == '.') { | |
if (f->d_name[1] == '\0') continue; | |
if (f->d_name[1] == '.' && f->d_name[2] == '\0') continue; | |
} | |
++r; | |
if (f->d_type == DT_DIR) { | |
name_len = strlen(f->d_name); | |
path[n] = '/'; | |
memcpy(&path[n + 1], f->d_name, | |
name_len + 1); // strcat(path, "/"); strcat(path, f->d_name); | |
r += count(path, n + 1 + name_len); | |
path[n] = '\0'; | |
} | |
} | |
closedir(d); | |
return r; | |
} | |
int main(int argc, char **argv) { | |
char path[PATH_MAX + 1]; | |
int c = 0; | |
if (!argv[1]) { | |
fprintf(stderr, "usage: %s path\n", argv[0]); | |
return EXIT_FAILURE; | |
} | |
for (++argv; *argv; ++argv) { | |
strcpy(path, *argv); | |
c += count(path, strlen(path)) + 1; // include top itself | |
} | |
printf("%d\n", c); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment