How can I tell if a given path is a directory or a file? (C/C++)


Question

I'm using C and sometimes I have to handle paths like

  • C:\Whatever
  • C:\Whatever\
  • C:\Whatever\Somefile

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

1
39
12/23/2016 8:36:24 AM

Accepted Answer

Call GetFileAttributes, and check for the FILE_ATTRIBUTE_DIRECTORY attribute.

28
9/28/2008 10:47:41 PM

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_IFREG )
    {
        //it's a file
    }
    else
    {
        //something else
    }
}
else
{
    //error
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon