Home > C++, VC++, MFC, Windows API > Using SearchPath!

Using SearchPath!

If you want to search for file in a given path use SearchPath API. Read MSDN documentation on this function.

If no path is given while calling SearchPath API, it searches in the following order(as per MSDN).

  1. The directory from which the application loaded.
  2. The current directory.
  3. The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.
    Windows NT/2000/XP: The name of this directory is SYSTEM32.
  4. Windows NT/2000/XP: The 16-bit Windows system directory. There is no function that retrieves the path of this directory, but it is searched. The name of this directory is SYSTEM.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.

Last option is interesting, if you feel that PATH environment variable does not include an addtional path(which should also have been in the PATH environment variable) then you can modify your PATH environment variable before calling SearchPath.

I recently did the same thing while I had to search for windows drivers in the PATH variable but C:\…\System32\Drivers path is not in the PATH variable, hence I add that too for my application before calling SearchPath. Pretty useful!

Here is a simple wrapper function which calls SearchPath

bool FindFile( LPCTSTR lpctszFileName_i, CString& csFilePath_o )
    const int nAllocLength = MAX_PATH * 2;
    TCHAR szPathBuffer[ nAllocLength ] = { 0 };  

    // Search for file
    if( SearchPath( 0, lpctszFileName_i, 0, nAllocLength, szPathBuffer, 0 ))
        csFilePath_o = szPathBuffer;
        return true;

    return false;
}// End FindFile
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: