All about programming in GNU/LINUX

Illustration of readdir and opendir GNU/LINUX system calls

//***HACKINTOSH RAO \m/ ****** CODE RUNS ONLY UNDER GNU/LINUX *****
//Program to print the contents of the Directory whose path is given as Input
/* system calls used
   1)opendir         prototype:DIR *opendir(path string)   //returns pointer to datatype DIR
   2)readdir         prototype:dirent *readdir(DIR *dp)    //info abt readdir is given below in the code
*/
#include<sys/stat.h>
#include<dirent.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
    DIR *dp;
    char *path;
    path=(char *)malloc(400);
    printf(“\nEnter the path: “);//Enter the path of the directory to be scanned
    scanf(“%s”,path);//Recieving a string using scanf has a potential buffer overflow vulnerabilty
    //use fgets instead of scanf
    //fgets(path,100,stdin);
    struct dirent* folder;
    dp=opendir(path);
    if(dp==NULL)
    {
        printf(“\nError Opening the directory”);
        exit(0);
    }
    printf(“\nThe contents of this directory are “);
    /*The readdir system call returns a pointer to the built in structure “dirent” (found in dirent.h)
      on succesive calls to readdir it returns pointer to the next entry in the directory
      readdir returns a NULL on reaching end of the directory after printing all its entries*/
    while((folder=readdir(dp))!=NULL)

    {
        printf(“\n\t%s “,folder->d_name);//name is the member of the structure dirent.
        //folder now contains the pointer to the structure dirent, so its to access the members of the structure
    }
    printf(“\nThank you ***************”);
    return 0;

}
//mail me at kartronics85@yahoo.com

Advertisements

2 responses

  1. SHAHID Nx

    super….. got what i was looking for.. thanks

    June 26, 2012 at 4:58 am

    • thank you , do follow the blog for more on linux!!

      June 26, 2012 at 11:30 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s