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

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

Answers


Call GetFileAttributes, and check for the FILE_ATTRIBUTE_DIRECTORY attribute.


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
}

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


On Windows you can use GetFileAttributes on an open handle.


If you're using CFile you can try

CFileStatus status;
    if (CFile::GetStatus(fileName, status) && status.m_attribute == 0x10){
       //it's directory
}

Easier to try FileInfo.isDir() in qt


Need Your Help

How to assign Woocommerce Product ID in Jquery

variables woocommerce

While using Woocommerce Product Addons, I am fitting a datepicker for specific input fields.

Why is Mongrel failing to pick up the correct HTTP verb?

ruby-on-rails routing mongrel

I have an extremely simple routes.rb in my Rails app:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.