Friday, May 11, 2012

Directory and sub directory file searching using c language



#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include .h>
/* limits.h defines "PATH_MAX". */
#include .h>
void listdir (const char *path){
    DIR *pdir = NULL;
    pdir = opendir (path);
    struct dirent *pent = NULL;
    if (pdir == NULL) {
        return; // exit the function
    } // end if
    while (pent = readdir (pdir)) {
        if (pent == NULL) {
            return;
        }
        //printf ("%s\n", pent->d_name);
        if (strcmp (pent->d_name, "..") != 0 &&
                strcmp (pent->d_name, ".") != 0) {
                int path_length;
                char newpath[PATH_MAX];
                path_length = snprintf (newpath, PATH_MAX, "%s/%s", path, pent->d_name);
                printf ("%s\n", newpath);
             
                if (path_length >= PATH_MAX) {
                    fprintf (stderr, "Path length has got too long.\n");
                    exit (EXIT_FAILURE);
                }
                listdir(newpath);
        }
    }
    closedir (pdir);
}
int main(int argc, char *argv[])
{
  listdir ("EMS");
  system("PAUSE");  
  return 0;
}