recursively descends a directory hierarchy in c

Solutions on MaxInterview for recursively descends a directory hierarchy in c by the best coders in the world

showing results for - "recursively descends a directory hierarchy in c"
Juliana
29 Oct 2016
1/**
2 * C program to list contents of a directory recursively.
3 */
4
5#include <stdio.h>
6#include <string.h>
7
8void listFilesRecursively(char *path);
9
10
11int main()
12{
13    // Directory path to list files
14    char path[100];
15
16    // Input path from user
17    printf("Enter path to list files: ");
18    scanf("%s", path);
19
20    listFilesRecursively(path);
21
22    return 0;
23}
24
25
26/**
27 * Lists all files and sub-directories recursively 
28 * considering path as base path.
29 */
30void listFilesRecursively(char *basePath)
31{
32    char path[1000];
33    struct dirent *dp;
34    DIR *dir = opendir(basePath);
35
36    // Unable to open directory stream
37    if (!dir)
38        return;
39
40    while ((dp = readdir(dir)) != NULL)
41    {
42        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
43        {
44            printf("%s\n", dp->d_name);
45
46            // Construct new path from our base path
47            strcpy(path, basePath);
48            strcat(path, "/");
49            strcat(path, dp->d_name);
50
51            listFilesRecursively(path);
52        }
53    }
54
55    closedir(dir);
56}}
similar questions