Solved

Search utility

Posted on 2004-08-09
16
413 Views
Last Modified: 2013-11-20
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.
0
Comment
Question by:tahadude
  • 8
  • 5
  • 2
  • +1
16 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 11754950
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.
0
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 11754998
BTW, there are also

http://www.codeproject.com/file/cfilefinderex.asp ("CFileFinder - Extend the functionality of CFileFind MFC class")

and

http://www.codeproject.com/file/fileglob.asp ("Recursive patterned File Globbing")
0
 
LVL 7

Expert Comment

by:vijay_visana
ID: 11759726
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
0
 
LVL 86

Expert Comment

by:jkr
ID: 11764775
>> you can use FindFirstFile and FindNextFile

Do you read previous comments?
0
 

Author Comment

by:tahadude
ID: 11765934
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
0
 
LVL 86

Expert Comment

by:jkr
ID: 11765995
>>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()'
0
 
LVL 5

Expert Comment

by:Nass89
ID: 11769641
>>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!
0
 
LVL 7

Expert Comment

by:vijay_visana
ID: 11769762
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?
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 86

Expert Comment

by:jkr
ID: 11777411
>>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!


0
 

Author Comment

by:tahadude
ID: 11779213
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.
0
 
LVL 86

Expert Comment

by:jkr
ID: 11779872
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.
0
 

Author Comment

by:tahadude
ID: 11805648
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?

0
 
LVL 86

Expert Comment

by:jkr
ID: 11805675
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'.
0
 

Author Comment

by:tahadude
ID: 11805800
I have declared it as UINT ThreadFunc(LPVOID pParam);

I probably need to make it static.

yes it worked by declaring it static.
Thanks
0
 

Author Comment

by:tahadude
ID: 11806012
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
0
 
LVL 86

Expert Comment

by:jkr
ID: 11806304
>>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...
}
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Running shell command from Access 3 63
Error on moodle after upgrade 3 107
fizzArray2 challenge 1 61
Detect file exist or not 3 83
This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
Introduction: Database storage, where is the exe actually on the disc? Playing a game selected randomly (how to generate random numbers).  Error trapping with try..catch to help the code run even if something goes wrong. Continuing from the seve…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now