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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check Directory exists 2

Status
Not open for further replies.

shetlandbob

Programmer
Mar 9, 2004
528
GB
I'm try to detect if a directory exists, using
Code:
  if ( fopen ( "C:\\MyDir", "r" ) )
  {
    directoryFound = true
  }
  else 
  {
    directoryFound = false
  }
this code cant find my directory but if I use:
Code:
  if ( fopen ( "C:\\MyDir\\myfile.txt", "r" ) )
  {
    directoryFound = true
  }
  else 
  {
    directoryFound = false
  }
it finds it??? any ideas whats wrong with the first code?
 
fopen doesn't serve to open directories, it is only for files.

Use this function to test whether the directory exists:
Code:
BOOL existsFolder(const CString & folderName)
{
	WIN32_FIND_DATA data;
	HANDLE hFile = FindFirstFile(folderName, &data);

	if ( hFile == INVALID_HANDLE_VALUE ) // directory doesn't exist
		return FALSE;
	else 
	{
		// is it folder or file?
		FindClose(hFile);
		if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			return TRUE;
		return FALSE;
	}
}

Standa K.
 
you can also check out the simplest shell API extension function PathFileExists.

like this

#include <windows.h>
#include <shlwapi.h>
#pragma comment (lib, "shlwapi")

int main(int argc, char *argv[])
{
BOOL b = PathFileExists("C:\\Program Files");
return 0;
}

HTH,




s-)

Blessed is he who in the name of justice and goodwill, sheperds the weak through the valley of darkness...
 
Sweet Ionel! I was still using the StandaK way, which is tried and true. There are so many api calls and this one makes things much easier.

Thanks again
Matt
 
Thank you. You should check all the function from shlwapi.dll (look for PathFileExists in MSDN then click locate)

I am sure you will find many other useful functions like PathAddBackslash, PathStripToRoot etc.

See you,

s-)

Blessed is he who in the name of justice and goodwill, sheperds the weak through the valley of darkness...
 
Also you may use GetFileAttrigutes("path") == -1 then file does not exist

Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top