Revert "Add comment warning about static variable usage in multi threading environments"
[eleutheria.git] / fileops / listdir_recursive.c
blobacae8ecf3d3789ca2b31a7940351321a377d0720
1 /* compile with:
2 gcc listdir_recursive.c -o listdir_recursive -Wall -W -Wextra -ansi -pedantic */
4 #include <dirent.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
10 int listdir(const char *path)
12 struct dirent *pdent;
13 DIR *pdir;
14 char *newpath = NULL;
15 static unsigned int dirdepth = 0;
16 unsigned int i;
18 /* open directory named by path, associate a directory stream
19 with it and return a pointer to it
21 if ((pdir = opendir(path)) == NULL) {
22 perror("opendir");
23 return -1;
26 /* get all directory entries */
27 while((pdent = readdir(pdir)) != NULL) {
28 /* indent according to the depth we are */
29 for (i = 0; i < dirdepth; i++)
30 printf(" ");
32 /* print current entry, or [entry] if it's a directory */
33 if (pdent->d_type == DT_DIR)
34 printf("[%s]\n", pdent->d_name);
35 else
36 printf("%s\n", pdent->d_name);
38 /* Is it a directory ? If yes, list it */
39 if (pdent->d_type == DT_DIR
40 && strcmp(pdent->d_name, ".")
41 && strcmp(pdent->d_name, "..")) {
42 dirdepth++;
44 /* allocate memory for new path
45 don't forget +1 for the '\0'
47 if ((newpath = malloc(strlen(path) + strlen(pdent->d_name) + 2)) == NULL) {
48 perror("malloc");
49 return -1;
52 /* construct new path */
53 strcpy(newpath, path);
54 strcat(newpath, "/");
55 strcat(newpath, pdent->d_name);
57 /* to iterate is human, to recurse, divine */
58 if (listdir(newpath) == -1) {
59 closedir(pdir);
60 free(newpath);
61 return -1;
66 closedir(pdir);
67 if (newpath != NULL)
68 free(newpath);
70 dirdepth--;
71 return 1;
74 int main(int argc, char *argv[])
76 /* check argument count */
77 if (argc != 2) {
78 fprintf(stderr, "Usage: %s directory\n", argv[0]);
79 exit(EXIT_FAILURE);
82 (void)listdir(argv[1]);
84 return EXIT_SUCCESS;