Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Searching for files and directories is something we, as programmers, have to do in many projects. I have always thought that there must be something someone out there wrote to make my life easier in this regard. I have done a lot of looking around but most of what I've found has had a dependency on a specific IDE, like VS and MFC for example. So, I decided to write my own, make it IDE independent and add some useful features. FindFile, is the result of my efforts.

Using the code

The code that allows searching consists of the files FindFile.h, FindFile.cpp, wildcard.h, and wildcard.cpp. To use the code, you need to initialize a FindFileOptions_t structure and pass it by reference to the constructor of FindFile. Here is a snippet of the structure, listing options used by FindFile:

struct FindFileOptions_t
{
    bool recursive;         // Whether to look inside subdirectories

    bool returnFolders;     // Return folder names as results too


    bool *terminateValue;   // Value to check to see whether search 

                            // should be terminated


    string location;        // Where to search for files


    string filter;          // Filter for files to be included


    string excludeFile;     // Exclude filter for files

    string excludeDir;      // Exclude filter for directories

};

Some of these options require explaining. The returnFolders option specifies whether FindFile should return both files and directories in its return results. The terminateValue option is a pointer to some integer in memory whose value will be read to determine whether the search should be aborted. This is useful to have when incorporating this class in a multi-threaded environment (as is most likely the case). If the value in the integer pointed to by terminateValue is anything but 0 the search will abort. If you do not want to use this feature, just set terminateValue to NULL.

Here is an example of a program that uses FindFile:

    FindFileOptions_t opts;
    opts.excludeDir = "CSE*;*53*";
    opts.excludeFile = "*.pdf;*.doc";
    opts.filter = "*";
    opts.location = "C:\\School";
    opts.recursive = true;
    opts.returnFolders = false;
    opts.terminateValue = NULL;

    FindFile find(opts);
    find.search();

    int nfiles = (int) find.filelist.size();
    __int64 size = find.listsize;

    // Print out the list of files found

    for (int i = 0; i < (int) find.filelist.size(); i++)
    {
        string fullname = FindFile::combinePath(find.filelist[i].path, 
                       find.filelist[i].fileinfo.cFileName);
        printf("%s\n", fullname.c_str());
    }

    printf("Found: %d files (%ld bytes)", nfiles, size);

This example will recursively search for all files in directory "C:\School" which do not have a PDF or DOC extension and will not look for files in subdirectories that begin with "CSE" or contain "53".

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralAdd Sort features
ekey
1:47 1 Jul '09  
Hi Louka,
Thank you post this aritical, it very useful for me, I added sort files by created time function, and post the code here, maybe you can merge the code into your source code:
FindFile.h:
enum OrderType
{
     None,
     CreateTimeAsc,
     CreateTimeDesc
};
// Specifies settings to use for searching for files
struct FindFileOptions_t
{
      bool recursive;            // Whether to look inside subdirectories
      bool returnFolders;      // Return folder names as results too

      bool *terminateValue;   // Value to check to see whether search should be
                                          // terminated

      string location;            // Where to search for files

      string filter;               // Filter for files to be included

      string excludeFile;      // Exclude filter for files
      string excludeDir;         // Exclude filter for directories

      OrderType orderType;      // FileList order type
};

FindFile.cpp:
struct AscendingFileCreateTimeSort
{
     bool operator()(const FileInformation &rpStart,const FileInformation &rpEnd)
      {
          return CompareFileTime(&rpStart.fileinfo.ftCreationTime ,&rpEnd.fileinfo.ftCreationTime) < 0;
      }
};

struct DescendingFileCreateTimeSort
{
     bool operator()(const FileInformation&amp; rpStart,const FileInformation&amp; rpEnd)
      {
          return CompareFileTime(&rpStart.fileinfo.ftCreationTime ,&rpEnd.fileinfo.ftCreationTime) > 0;
      }
};

void FindFile::search ()
{
      clear();
      scanPath (m_opts.location);
     switch(m_opts.orderType)
     {
     case OrderType::CreateTimeAsc:
          sort(filelist.begin(),filelist.end(),AscendingFileCreateTimeSort());            
                        break;
     case OrderType::CreateTimeDesc:
          sort(filelist.begin(),filelist.end(),DescendingFileCreateTimeSort());
          break;
     default:
          break;
     }
}

Best wishes,
Yun
Generalanother thank you !!
masotta
6:45 9 Dec '08  
Simple, clear and effective ...
GeneralTime to place a "Thank you"
ubentz
6:28 21 Dec '06  
Hi Louka,

i just found your code and it fits exactly to what i was looking for !
Thank you very much ! So i do not need to do things again that others already did ...

Greetz Uwe


GeneralCase sensitivity in filter [modified]
gugy1
0:09 14 Jun '06  
Hi,

I have tested the class and found it easy to use and working correctly.
There is only one thing i have found to be the problem, at least in my case.
I have files with same extension but in different character cases.
For example: MYFILE_1.txt and MYFILE2.TXT
Although I can specify m_opts.filter = "*.txt;*.TXT" to get both files in result set, it seems a bit impractical to put into filter all possible user inputed combinations like: *.TxT;*.txT etc.

It would be nice if case sensitive/insensitive option is added to struct FindFileOptions_t and handled in the code.



Gugy

GeneralVisual C++ 2005 Express Compiler Error
gary_johnson_53
7:06 8 Mar '06  
The short story is I get
1>C:\Program Files\Microsoft Visual Studio 8\VC\include\crtdbg.h(970) : error C2059: syntax error : '('

Why I get his message is beyond me.

Further research show that C2059 can be caused by a number of passing a structure type problems
example

Another specific reason you can get C2059 is when you compile an application that specifies a structure in the default arguments for a function. The default value for an argument must be an expression. An initializer list, such as that used to initialize a structure, is not an expression. The resolution is to define a constructor to perform the required initialization.

Does anyone know how to fix this and get the fixes posted here for other users?
A google search Louka Dlagnekov shows him at UCSD - University of California at San Diego
Louka, if you read this, thanks, and have you thought about a way to keep this updated. I use this in a global search and replace for large amounts of text between two tags.

The error details are here

>Compiling...
1>FindFile.cpp
1>C:\Program Files\Microsoft Platform SDK for Windows XP SP2\Include\specstrings.h(334) : warning C4005: '__reserved' : macro redefinition

....
...
1> C:\Program Files\Microsoft Visual Studio 8\VC\include\sal.h(500) : see previous definition of '__in_ecount'
1>C:\Program Files\Microsoft Platform SDK for Windows XP SP2\Include\specstrings.h(358) : warning C4005: '__inout_ecount' : macro redefinition
1> C:\Program Files\Microsoft Visual Studio 8\VC\include\sal.h(528) : see previous definition of '__inout_ecount'
1>C:\Program Files\Microsoft Platform SDK for Windows XP SP2\Include\specstrings.h(359) : warning C4005: '__out_bcount' : macro redefinition
1> C:\Program Files\Microsoft Visual Studio 8\VC\include\sal.h(510) : see previous definition of '__out_bcount'
1>C:\Program Files\Microsoft Platform SDK for Windows XP SP2\Include\specstrings.h(360) : warning C4005: '__in_bcount' : macro redefinition
1> C:\Program Files\Microsoft Visual Studio 8\VC\include\sal.h(501) : see previous definition of '__in_bcount'
1>C:\Program Files\Microsoft Platform SDK for Windows XP SP2\Include\specstrings.h(361) : warning C4005: '__inout_bcount' : macro redefinition
1> C:\Program Files\Microsoft Visual Studio 8\VC\include\sal.h(529) : see previous definition of '__inout_bcount'
1>C:\Program Files\Microsoft Visual Studio 8\VC\include\crtdbg.h(970) : error C2059: syntax error : '('
1>C:\Program Files\Microsoft Visual Studio 8\VC\include\crtdbg.h(974) : error C2059: syntax error : '('



Generalno unicode
Jan VO
0:13 14 Nov '05  
The class "wildcard" is not up to Unicode paths (it's full of char*) !
Generalbug in wildcard
heroboy
19:02 5 Sep '05  
"1?" match "1"
"?1" match "1"
"1?2" match "12"
...
GeneralSource code link failure
Eckman
2:27 16 Aug '05  
Hi there,

Would it be possible for you to please email me the zip file with the source code? code project's website download button doesn't seem to have the file available.
email:eck@tuks.co.za

I'd be very thankful if u could send it to me,
kind regards
Eckhard.
Generallink error
densitet
3:33 3 Mar '05  
Hi, I'm programming a client server with sockets and i need that the server sends mea message with the list of all the files and folders of c:\ and i wrote in other thread and the people told me that i have to look this project but i'm no very good programming with vs6 and c++ i'm little bit new and i'm cheking this program but i have a link error in the beggining "FindFile error LNK2019: unresolved external symbol _main referenced in function _mainCRTStartup" and i don't know why, i have read the article and i don't know where i have to inizializate the settings.

Can somebody help me?

Thank you so much
GeneralRe: link error
Louka Dlagnekov
8:12 3 Mar '05  
I don't know how you've set up your VS project, but it sounds like none of the source files in your project have a main() function, which is the entry point of all programs. Keep in mind that the source files in this article don't form a stand alone program; you need to be calling its functions from some sort of a driver program.
GeneralRe: link error
densitet
5:43 4 Mar '05  
I'm only cheking your program and i'm inizializated like you say in the article in FindFile.cpp in the begining FindFile but when i build, visual studio show me this error "FindFile error LNK2019: unresolved external symbol _main referenced in function _mainCRTStartup", and i don't know why.

Thanks
/densitet
Generallinking error in msvc6 with stlport 4.6.2
bektek
17:18 15 Sep '04  
error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __thiscall _STL::allocator::deallocate(char *,unsigned int)const " (__imp_?deallocate@?$allocator@D@_STL@@QBEXPADI@Z)

I'd got this error, do you know why?

only with this filefind library, this happen Smile
GeneralRe: linking error in msvc6 with stlport 4.6.2
Louka Dlagnekov
18:12 15 Sep '04  
Perhaps this discussion can help:

http://crayzedsgui.sourceforge.net/modules.php?name=Forums&file=viewtopic&t=93

Louka
GeneralRe: linking error in msvc6 with stlport 4.6.2
bektek
20:43 15 Sep '04  
the web page was relly helpful..
now it works well..
Thanks your info..

something _DEBUG flag fix the problem..

GeneralSearch differect hard drives with one location...
CyberJay82
9:27 26 Jul '04  
Is it possible to search all of a computers hardrives without knowing the drive letters, example my one computer has only one drive (C:\) and my desktop has two drives (C:\ and F:\). So i want to specify one location like a wildcard or something so that it will search all hardrives whether it be one or many drives?
GeneralRe: Search differect hard drives with one location...
Louka Dlagnekov
16:29 26 Jul '04  
CyberJay82,

You could call GetLogicalDrives() which returns a bit mask that has a bit set for each logical drive on the machine. If the highest order bit is set it means there's an A:\, if the next highest order bit is set, there's a B:\, etc. Then you can call GetDriveType() on each such drive and check the return value against DRIVE_FIXED to determine whether it is a hard disk.

There's a detailed article on how to do this here:

http://msdn.microsoft.com/msdnmag/issues/04/01/CQA/default.aspx

Louka

GeneralVS and MFC Solutions:
Alan Phang SP
20:26 7 Mar '04  
Louka,

As you mentioned in the introduction, you've found the solutions, which are IDE dependent (VS or MFC), for the same task of file find. Would you share your findings and source codes?

Thanks in advance.



Alan Phang SP
GeneralRe: VS and MFC Solutions:
Louka Dlagnekov
20:30 7 Mar '04  
Alan,

The code that is posted on this page is, in fact, IDE independent. You can compile it with VS, Borland C++/Borland C++ Builder or some other Windows IDE and it will work.

Louka
GeneralHelp NEEDED PLEASE!!
Zero_consequences
21:54 13 Jan '04  
Hi, Does anyone know how to use the windows search api to search for a WORD or phrase in files. Is there any sample code or snippets that could help me do this.

Thanks,
Gav.
GeneralRe: Help NEEDED PLEASE!!
Louka Dlagnekov
16:53 18 Jan '04  
Gav,

You will need to process each found file on your own to determine whether each matches the desired word/phrase. Just open each file, read sections into a buffer and search for the word in the buffer. It gets a little tricky if part of the word matches the end of the current buffer. If that happens, you'll need to try a match with the beginning of the second buffer.

Cheers,

Louka
GeneralGerman Umlaute (and probably other special characters)
ToK78
6:38 3 Jan '04  
Hi,

the program does find files that contain "Umlaute" (äöü) but it never finds any files if the path contains an Umlaut.
I found out that the problem is with the FindFirstFile/FindNextFile commands.
Anyone any idea what I can do?

Tobias
Generaldu* matches data.txt
L e P o
3:27 25 Nov '03  
Hi,

I guess there's bug in the code: pattern du*
matches all files and directories starting with d.

In addition, it always finds files starting with hyphen, but I guess that's not so terrible...

Does anyone have a fix for the first one?

--
LePo D'Oh!
GeneralRe: du* matches data.txt
DirkS
20:47 18 Jan '04  
Hi,

maybe you should use PathMatchSpec() declared in Shlwapi.h instead of the home made wildcard class.

DS
GeneralFantastic!
Joe McConnell
7:55 19 Nov '03  
Louka,

Just wanted to say thanks for writing and releasing this. It works great (with the small fix mentioned above).

Thank you,

Joe

-= Joe McConnell =-
Generalfound a possible error...please help
agd011
12:28 26 Jun '03  
Hi,
When I run the program, I do not get complete results. for example, if I run the program searching on "C:\\" for "*.txt" files.....I have a folder labeled "aab" (for testing purposes) that contains text files that the program does not find. The program skips over this folder everytime instead of finding it first. any ideas on this one??
I love this program though, it is very useful! I've been trying to debug this error, but I can't figure it out.

thank you in advance for any help

Alex


Last Updated 13 Jan 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010