Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to check professionally if a directory exist? 3

Status
Not open for further replies.

sulacco

Technical User
Nov 8, 2002
74
RU
How to check professionally if a directory exist?
 
Well "professionally" I think you'd want to be compattible on more than just Windows, so I'd do something like this:
Code:
#include <io.h>   // For access().
#include <sys/types.h>  // For stat().
#include <sys/stat.h>   // For stat().
#include <iostream>
#include <string>
using namespace std;

int main( void )
{
    string strPath;
    cout << "Enter directory to check: ";
    cin >> strPath;

    if ( access( strPath.c_str(), 0 ) == 0 )
    {
        struct stat status;
        stat( strPath.c_str(), &status );

        if ( status.st_mode & S_IFDIR )
        {
            cout << "The directory exists." << endl;
        }
        else
        {
            cout << "The path you entered is a file." << endl;
        }
    }
    else
    {
        cout << "Path doesn't exist." << endl;
    }

    return 0;
}
 
Here's a function that I use to check if a folder exists:

Code:
BOOL FolderExists(CString strFolderName)
{   
	return GetFileAttributes(strFolderName) != INVALID_FILE_ATTRIBUTES;   
}
of course, this will also return true whether it's a file or folder. BTW, I use this function to get a folder:

Code:
CString GetFolder()
{
                                               LPMALLOC pMalloc;
                                                CString strDirectory;
			BROWSEINFO bi;
			
			/* Gets the Shell's default allocator */
			char pszBuffer[MAX_PATH];
			LPITEMIDLIST pidl;
			// Get help on BROWSEINFO struct - it's got all the bit settings.
			bi.hwndOwner = GetDesktopWindow();
			bi.pidlRoot = NULL;
			bi.pszDisplayName = pszBuffer;
			bi.lpszTitle = _T("Select First Directory");
			bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
			bi.lpfn = NULL;
			bi.lParam = 0;

			
			if (::SHGetMalloc(&pMalloc) == NOERROR)
			{
				if ((pidl = ::SHBrowseForFolder(&bi)) != NULL)
				{
					if (::SHGetPathFromIDList(pidl, pszBuffer))
					{ 
						strDirectory = pszBuffer;
					}
					pMalloc->Free(pidl);
				}
				pMalloc->Release();
			}
                                                return strDirectory;
}

BlackDice

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top