This blog is under construction

Monday, 29 July 2013

C program to list all files in a directory

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


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

  int main() {
        DIR *dir;
        struct dirent *ent;
        char dname[MAX];

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

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

        if (!dir) {
                printf("Given directory does not exists!!\n");
                return 0;
        }

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

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

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ls -a mydir/
  .  ..  data.txt  editMe.txt  output.txt

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






SEE ALSO

    No comments:

    Post a Comment