2 gcc listdir_recursive.c -o listdir_recursive -Wall -W -Wextra -ansi -pedantic */
10 int listdir(const char *path
)
15 static unsigned int dirdepth
= 0;
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
) {
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
++)
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
);
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
, "..")) {
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
) {
52 /* construct new path */
53 strcpy(newpath
, path
);
55 strcat(newpath
, pdent
->d_name
);
57 /* to iterate is human, to recurse, divine */
58 if (listdir(newpath
) == -1) {
74 int main(int argc
, char *argv
[])
76 /* check argument count */
78 fprintf(stderr
, "Usage: %s directory\n", argv
[0]);
82 (void)listdir(argv
[1]);