tags:

views:

607

answers:

4

I'm using C and sometimes i have to handle paths like C:\Whatever, C:\Whatever\ or C:\Whatever\Somefile

Is there a way to check if a given path is a directory or a given path is a file? :O

A: 

On Windows you can use GetFileAttributes on an open handle.

Scott Danahy
+6  A: 

Call GetFileAttributes, and check for the FILE_ATTRIBUTE_DIRECTORY attribute.

Colen
If you need to support Windows 98, then you can't use this function. See my answer about PathIsDirectory below if you need Win98 support.
jeffm
+13  A: 

stat() will tell you this.

struct stat s;
if( stat(path,&s) == 0 )
{
    if( s.st_mode & S_IFDIR )
    {
        //it's a directory
    }
    else if( s.st_mode & S_ISREG )
    {
        //it's a file
    }
    else
    {
        //something else
    }
}
else
{
    //error
}
the only problem I have with this code is the comment in the else case. Just because something isn't a directory doesn't mean it's a file.
dicroce
@dicroce: Yep, true enough; fixed.
+1  A: 

In Win32, I usually use PathIsDirectory and its sister functions. This works in Windows 98, which GetFileAttributes does not (according to the MSDN documentation.)

jeffm