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

how to validate path 1

Status
Not open for further replies.

gacaccia

Technical User
May 15, 2002
258
US
hi all,

trying to make a simple c++ console application. it takes a path specified by a user and updates some configuration files with the new info. how do i validate the path? i know how to validate the existance of a file, but not a folder.

thanks,

glenn
 
Code:
#include <windows.h>

DWORD dwAttributes = GetFileAttributes ( &quot;C:\\Is\\This\\A\\Directory&quot; );
if ( dwAttributes == 0xffffffff )
   { // GetFileAttributes failed
     // call GetLastError ( ) to find out why
   } else
   { if ( dwAttributes & FILE_ATTRIBUTE_DIRECTORY )
        { // It is a directory
        } else
        { // it is not a directory
        } }


Marcel
 
one problem i just noticed with the above mentioned solution, it doens't work if the path is to the root of a drive. how would i validate a path in this case?

thanks,

glenn
 
glenn,

I have no problem with the code above. Perhaps it is os-dependent (i use xp pro)? Problem might be with some older os a trailing backslash is required for the root and not for subdirs. Try using &quot;X:\\&quot; instead of &quot;X:&quot;.

If that doesn't help, test for a root yourself. Change the code like this:


BOOL fIsRootValid ( char *Name )
{
if ( Name == NULL )
{ return FALSE; }
if ( strlen ( Name ) < 2 || strlen ( Name ) > 3 )
{ return FALSE; }
char Root[4];
strcpy ( Root, Name );
if ( strlen ( Root ) == 2 )
{ strcat ( Root, &quot;\\&quot; ); }
UINT uType = GetDriveType ( Root );
switch ( uType )
{ case DRIVE_UNKNOWN :
case DRIVE_NO_ROOT_DIR :
return FALSE;
case DRIVE_REMOVABLE :
case DRIVE_FIXED :
case DRIVE_REMOTE :
case DRIVE_CDROM :
case DRIVE_RAMDISK :
return TRUE;
default :
return FALSE; }
return FALSE; }


BOOL fIsDirValid ( char *Dirname )
{
if ( Dirname == NULL )
{ return FALSE; }
if ( strlen ( Dirname ) == 2 &&
*( Dirname + 1 ) == ':' )
{ return fIsRootValid ( Dirname ); }
if ( strlen ( Dirname ) == 3 &&
*( Dirname + 1 ) == ':' &&
*( Dirname + 2 ) == '\\' )
{ return fIsRootValid ( Dirname ); }
DWORD dwAttributes = GetFileAttributes ( Dirname );
if ( dwAttributes == 0xffffffff )
{ return FALSE; }
if ( dwAttributes & FILE_ATTRIBUTE_DIRECTORY )
{ return TRUE; }
return FALSE; }





Marcel
 
oops, my mistake in using your previous code. you're right, it does work. thanks again and for the additional examples.

glenn
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top