Pages

Tuesday, April 18, 2017

Display All The Files From A Directory Using C

Display All The Files From A Directory Using C


DESCRIPTION:
  • This program get the directory path from the user and display all the filed from the directory.
  • We should add dirent.h header file to accomplish this program.


PROGRAM:

#include <stdio.h>

#include <string.h>

#include <dirent.h>
int main (int argc, char *argv[])
{
    DIR *directory;
    struct dirent *file;    
    directory = opendir (argv[1]);
    int directory_length = strlen(argv[1]);
    if (directory != NULL){
        while (file = readdir (directory))
                  printf("FILE : %s ",file->d_name);

        (void) closedir (directory);
      }
      else
        perror ("Not able to open the directory ");
    return 0;
}



COMPILE

gcc -o out scan.c

RUN:
  • Pass the directory name with the path as argument to the program
./out /home/sujin/directory

OUTPUT:

FILE : favicon.ico
FILE : README.txt
FILE : monkey.jpg 
FILE : index.html



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.