We help IT Professionals succeed at work.

Directory Parsing

premadhas
premadhas asked
on
I'm trying to write some code to parse a directory structure to extract all
the cpp files with their path. Trying to use _findfirst and _findnext recursively
_findfirst("/*",dir) and findnext() gives list of files and directories in the current
drive. Unable to switch to the sub-directories and do a recursive search for the
cpp files. _getcwd and _chwd does'nt seem to work. They repeatedly give the
cpp files in the current directory and overflows. Can anyone help?
Comment
Watch Question

Commented:
no, you are doing it wrongly. You can't chdir(). You need to search, not for *.cpp, but for *.*, then you ignore all which are not .cpp and which are not directories.  You recursively start a new search for each subdirectory.

I have some code lying around & will post it if I can find it, but you have enough info already.
BRONZE EXPERT
Commented:
#include <stdio.h>        
#include <io.h>              
#include <direct.h>          
#include <fcntl.h>        
#include <sys\stat.h>    
#include <stdlib.h>
#include <string.h>

void spider_path(char *path)
{
     struct _finddata_t ff;
     long fhandle;
     char spath[256], fname[_MAX_FNAME], ext[_MAX_EXT];

     /* open the direcory */
     sprintf(spath,"%s\\*.*",path);
     if((fhandle = _findfirst(spath,&ff)) != -1)
     {
          /* loop through each entry */
          while(!_findnext(fhandle,&ff))
          {    
               if(ff.attrib & _A_SUBDIR)
               {
                    if(strcmp(ff.name,".."))
                    {
                         sprintf(spath,"%s\\%s",path,ff.name);
                         spider_path(spath);
                    }
               }
               else if(ff.attrib ^ _A_SYSTEM)
               {
                    /* extract the track name */
                    _splitpath(ff.name,NULL,NULL,fname,ext);          
                    printf("Found file %s%s\n",fname,ext);
/* you can examine the file extension here */
               }              
          }
          close(fhandle);
     }
}

void main()
{
     spider_path("D:\\bin");
}

Author

Commented:
Hi makerp
It works great. But for files in "D:\\bin" as per your example i.e., the root it gives wrong path
Any comments?

Explore More ContentExplore courses, solutions, and other research materials related to this topic.