Link to home
Start Free TrialLog in
Avatar of tahadude
tahadude

asked on

Search utility

Hi,

I am developing a file search utility in MFC. Can someone please give me tips as to how to go about doing this? I want to develop a utility which, given a file name, and a folder, will search for that file in the folder (and all sub-folders). Then it should copy the file and put it in another folder of my choice.

Any links to similar code would be extremely helpful.

Thanks.
Avatar of jkr
jkr
Flag of Germany image

You could use the following class:

#ifndef      __DIRTREE_H
#define __DIRTREE_H

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

class      CDirectoryTree
{
public:

                              CDirectoryTree      ();

                              CDirectoryTree      (      TCHAR*                        pszPath
                                                      );

      void                  TraverseTree      (      TCHAR*                        pszPath,
                                                            TCHAR*                        pszBase      =      NULL
                                                      );

      DWORD                  GetErrorCode      ()      const      {      return      (      m_dwError);};

private:

      virtual      void      HandleFile            (      WIN32_FIND_DATA*      pw32fd);
      virtual      void      HandleDirectory      (      WIN32_FIND_DATA*      pw32fd);

      DWORD                  m_dwError;

};

#endif      //      ndef      __DIRTREE_H

#include "stdafx.h"
#include <dirtree.h>

CDirectoryTree::CDirectoryTree  ()
{
    m_dwError   =   0;
}

CDirectoryTree::CDirectoryTree  (   TCHAR*  pszPath
                                )
{
    m_dwError   =   0;

    TraverseTree    (   pszPath);
}

void    CDirectoryTree::TraverseTree    (   TCHAR*  pszPath,    
                                            TCHAR*  pszBase
                                        )
{
    WIN32_FIND_DATA w32fd;
    HANDLE          hFind;
    DWORD           dwAtt;
    TCHAR           acPath  [   MAX_PATH]   =   "\0";
    TCHAR           acBase  [   MAX_PATH]   =   "\0";

    if  (   !pszPath)
            throw   _T("No Directory given!");

    if  (   '.' ==  *(  pszPath +   _tcslen (   pszPath)    -   1))
            return;

    if  (   pszBase)
        {
            if  (   !SetCurrentDirectory    (   pszBase))
                {
                    throw _T("setcwd() failed");
                }

            _stprintf   (   acPath, _T("%s\\%s"),   pszBase,    pszPath);
        }
    else
            _tcscpy (   acPath, pszPath);

    _tcscpy (   acBase, acPath);

    dwAtt   =   GetFileAttributes   (   acPath);

    if  (   0xffffffff  ==  dwAtt)
        {
            m_dwError   =   GetLastError    ();
           
            return;
        }

    if  (   FILE_ATTRIBUTE_DIRECTORY    &   dwAtt)
        {
            if  (   '\\'    ==  acPath  [   _tcslen (   acPath) -   1])
                    _tcscat (   acPath, _T("*.*"));
             else
                    _tcscat (   acPath, _T("\\*.*"));
        }


    hFind   =   FindFirstFile   (   acPath, &w32fd);

    if  (   INVALID_HANDLE_VALUE    ==  hFind)
        {
             // error

            m_dwError   =   GetLastError    ();
            throw m_dwError;

            return;
        }

    // recurse if directory...
    if  (   FILE_ATTRIBUTE_DIRECTORY    &   w32fd.dwFileAttributes)
        {
            TraverseTree    (   w32fd.cFileName,    acBase);
        }
     else
            HandleFile  (   &w32fd);

    while   (   FindNextFile (  hFind,  &w32fd))
            {
                // recurse if directory...
                if  (   FILE_ATTRIBUTE_DIRECTORY    &   w32fd.dwFileAttributes)
                    {
                        TraverseTree    (   w32fd.cFileName,    acBase);
                    }
                 else
                        HandleFile  (   &w32fd);
            }

    if  (   ERROR_NO_MORE_FILES !=  GetLastError())
        {
         // error
            m_dwError   =   GetLastError    ();
        }

    FindClose ( hFind);
}

void    CDirectoryTree::HandleFile      ( WIN32_FIND_DATA* pw32fd)
{
}

void    CDirectoryTree::HandleDirectory ( WIN32_FIND_DATA* pw32fd)
{
}

Now, all you need to do is to derive from this class and overwrite 'HandleFile()' to copy the file in another folder.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of vijay_visana
vijay_visana

you can use FindFirstFile and FindNextFile

Once I wrote a function to delete file in particular dir with lit'bit modification you can make it find file and move it to some other dir.

BOOL DeleteDir(CString& cstrDirPath)
{
      WIN32_FIND_DATA FindFileData;
      HANDLE hFind;
      CString cstrSrchDir;
      if(cstrDirPath[cstrDirPath.GetLength()-1] == '\\')
            cstrDirPath.SetAt(cstrDirPath.GetLength()-1, 0);
      cstrSrchDir.Format("%s\\*.*",cstrDirPath);


 
  hFind = FindFirstFile(cstrSrchDir,&FindFileData);
  if(hFind == INVALID_HANDLE_VALUE)
        return FALSE;
  FindNextFile(hFind,&FindFileData);
  FindNextFile(hFind,&FindFileData);      
  do      
  {
      CString cstrTemp;
    TRACE("The first file found is %s\n", FindFileData.cFileName);
      cstrTemp.Format("%s\\%s",cstrDirPath,FindFileData.cFileName);
    DeleteFile(cstrTemp);// user here CopyFile

  }while(FindNextFile(hFind,&FindFileData));
  FindClose(hFind);
  if(!RemoveDirectory((LPCTSTR)cstrDirPath))
  {
        TRACE("%d\n",GetLastError());
        
  }

  return TRUE;
      

}

Now to enum inner dir call this function from a function that is traversing the folders/subfolders
>> you can use FindFirstFile and FindNextFile

Do you read previous comments?
Avatar of tahadude

ASKER

Thanks for your help. I have one more question. Is there a function for copying files like CopyFile() available? If yes, in which class and how do I include it?
Appreciate your help
>>Is there a function for copying files like CopyFile() available? If yes, in which class and how do I include it?

Um, if you are talking about my example, you'd just place it in the 'HandleFile()' method. Regarding http://www.codeproject.com/file/cfilefinderex.asp you'd place the copy functionality in

void FileFinderProc(CFileFinder *pFinder,
        DWORD   dwCode, void    *pCustomParam);

that you'd supply by calling 'SetCallback()'
>>Is there a function for copying files like CopyFile() available?
use the CopyFile:

BOOL CopyFile(
  LPCTSTR lpExistingFileName, // name of an existing file
  LPCTSTR lpNewFileName,      // name of new file
  BOOL bFailIfExists          // operation if file exists
);

Good Luck!
CopyFile & CopyFileEx does exist and it is define in
Header: Declared in Winbase.h
Library: Use Kernel32.lib.


>> JKR
I did have look at your comment but it looks to complecated for me that is y I posted the comment I hope you understand my intention  It was not to copy your comments.
BTW Do you think that the solution I gave is all same as yours one?
>>BTW Do you think that the solution I gave is all same as yours one?

No, but you mainly pointed out these APIs that where already mentioned, so that was kinda unnecessary. If we start that kind of commenting, we'll end up with "unique" solutions like

Q: How do I add 2 and 3?

A1: int sum = 2 +3;
A2: unsigned long sum = 3 + 2; // AND THAT HASN'T BEEN MENTIONED BEFORE!


I am getting this wierd error on building my application. It was working well earlier, but this error has suddenly started coming up.

"Linking...
Path.obj : error LNK2001: unresolved external symbol __imp__PathUnquoteSpacesA@4
Path.obj : error LNK2001: unresolved external symbol __imp__PathRemoveArgsA@4
Path.obj : error LNK2001: unresolved external symbol __imp__PathGetArgsA@4
Path.obj : error LNK2001: unresolved external symbol __imp__PathFileExistsA@4
Path.obj : error LNK2001: unresolved external symbol __imp__PathCanonicalizeA@8
Path.obj : error LNK2001: unresolved external symbol __imp__PathRelativePathToA@20
Debug/fileview.exe : fatal error LNK1120: 6 unresolved externals
Error executing link.exe.
"
Its a linking error, and its probably something minor, but i don't know how to solve it. Please help.
Thanks.
Add Shlwapi.lib to yaour project - either by using

#pragma comment(lib,"Shlwapi.lib")

in one of your source files or use "Project|Add to Project|Files...", choose ".lib files" from the combo box, navigate to the directory where the it lives (usually, the 'lib' directory of VC++) and select the library.
I'm stuck once more.
I am trying to make a thread which would handle a progress bar in the background of my dialog box. I used the AfxBeginThread(<my thread function>, this) .
However I get this error every time:
'AfxBeginThread' : none of the 2 overloads can convert parameter 1 from type 'unsigned int (void *)'

I have declared my thread handler function as returning UINT.
I have included this funcion in the same class as the one I am calling it from- could that be a problem?

Is your thread proc declared like

UINT WINAPI MyThreadFunction( LPVOID pParam );

?

Remember that if it is a class member, it has to be declared as 'static'.
I have declared it as UINT ThreadFunc(LPVOID pParam);

I probably need to make it static.

yes it worked by declaring it static.
Thanks
Hi,
one more question: When I use CopyFile(), and it returns 0  i.e. fails, I want to know why it failed ex: File already exists, File is in use, Destination folder improper etc. How can i do that?

Also, while using the
http://www.codeproject.com/file/cfilefinderex.asp
code, is there any way i can check whether a particular folder exists- or must be created?

Waiting fro your reply
Taha
>>When I use CopyFile(), and it returns 0  i.e. fails, I want to know why it failed

Call 'GetLastError()' when the call fails to obtain extended error information.

>>is there any way i can check whether a particular folder exists- or must be created?

You could use

if ( -1 == GetFileAttributes("c:\\path\\somefolder")) {

    // ... does not exist...
}