Wednesday, April 20, 2011

Searching files in C on Windows

How would one search for files on a computer? Maybe looking for certain extensions.

I need to iterate through all the files and examine file names.

Say I wanted to find all files with an .code extension.

From stackoverflow
  • Use FindFirstFile()/FindNextFile() functions and a recursive algorithm to traverse subfolders.

  • For Windows, you would want to look into the FindFirstFile() and FindNextFile() functions. If you want to implement a recursive search, you can use GetFileAttributes() to check for FILE_ATTRIBUTE_DIRECTORY. If the file is actually a directory, continue into it with your search.

    Rob Kennedy : FindFirst/NextFile will already tell you the attributes of the file; not need to call GetFileAttributes.
  • FindFirstFile()/ FindNextFile() will do the job in finding the list of files in the directory. To do recursive search through the sub-directories you might use _splitpath

    to split the path, into directory and filenames, and then use the resulting directory detail to do a recursive directory search.

  • A nice wrapper for FindFirstFile is dirent.h for windows (google dirent.h Toni Ronkko)

    
    #define S_ISREG(B) ((B)&_S_IFREG)
    #define S_ISDIR(B) ((B)&_S_IFDIR)
    
    static void
    scan_dir(DirScan *d, const char *adir, BOOL recurse_dir)
    {
        DIR *dirfile;
        int adir_len = strlen(adir);
    
        if ((dirfile = opendir(adir)) != NULL) {
         struct dirent *entry;
         char path[MAX_PATH + 1];
         char *file;
    
         while ((entry = readdir(dirfile)) != NULL)
            { 
                struct stat buf;
          if(!strcmp(".",entry->d_name) || !strcmp("..",entry->d_name))
                    continue;
    
                sprintf(path,"%s/%.*s", adir, MAX_PATH-2-adir_len, entry->d_name);
    
                if (stat(path,&buf) != 0)
                    continue;
    
                file = entry->d_name;
                if (recurse_dir && S_ISDIR(buf.st_mode) )
                    scan_dir(d, path, recurse_dir);
                else if (match_extension(path) && _access(path, R_OK) == 0) // e.g. match .code
                    strs_find_add_str(&d->files,&d->n_files,_strdup(path));
         }
         closedir(dirfile);
        }
        return;
    }
    

0 comments:

Post a Comment