This blog is under construction

Monday, 29 July 2013

C program to list all files in a directory recursively

Write a C program to list all files in a directory recursively.


  #include <stdio.h>
  #include <dirent.h>
  #include <string.h>
  #define MAX 256

  void listFiles(char *dname) {
        DIR *dir;
        struct dirent *ent;
        char temp[MAX];

        /* open the given directory */
        dir = opendir(dname);

        if (!dir) {
                return;
        }

        /* list all files in the given directory directory */
        printf("Files in the directory - %s:\n", dname);
        while (ent = readdir(dir)) {

                printf("%s\n", ent->d_name);
                if (strcmp(ent->d_name, ".") == 0 ||
                        strcmp(ent->d_name, "..") ==0) {
                                continue;
                }

                /* form directory name relative to current directory */
                strcpy(temp, dname);
                strcat(temp, "/");
                strcat(temp, ent->d_name);

                /* recursive call to recursively list all files */
                listFiles(temp);
        }

        /* close the opened directory */
        closedir(dir);

        return;
  }

  int main() {
        char dname[MAX];

        /* get the file name from the user */
        printf("Enter your directory name:");
        fgets(dname, MAX, stdin);
        dname[strlen(dname) - 1] = '\0';

        /* lists all files in the given directory recursively */
        listFiles(dname);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ls -aR mydir
  mydir:
  .  ..  data.txt  editMe.txt  output.txt  sub1  sub2  sub3
  
  mydir/sub1:
  .  ..  file1.txt  file2.txt  file3.txt

  mydir/sub2:
  .  ..  file4.txt  file5.txt
  
  mydir/sub3:
  .  ..  file6.txt  file7.txt  sub4

  mydir/sub3/sub4:
  .  ..  file8.txt  file9.txt 


  jp@jp-VirtualBox:~/$ ./a.out
  Enter your directory name:mydir
  Files in the directory - mydir:
  editMe.txt
  data.txt

  output.txt
  sub1
  Files in the directory - mydir/sub1:
  .
  ..
  file1.txt
  file3.txt
  file2.txt
  sub2
  Files in the directory - mydir/sub2:
  .
  ..
  file5.txt
  file4.txt
  sub3
  Files in the directory - mydir/sub3:
  .
  ..
  file7.txt
  file6.txt
  sub4
  Files in the directory - mydir/sub3/sub4:
  .
  ..
  file8.txt
  file9.txt






SEE ALSO

    No comments:

    Post a Comment