Grant H.
Grant H.

Reputation: 3717

What's the cheapest way to know if a path refers to a folder or a file in c++?

I'm working with a shell extension overlay handler, and I'll be passed a path that I know to be valid, but I don't know if it's a folder or a file. This operation could be called relatively often, so I want to determine whether it's a file or folder as cheaply as possible. Using c++ (windows specific is fine for my requirements), how can I best accomplish this?

Upvotes: 1

Views: 179

Answers (6)

Alex K.
Alex K.

Reputation: 175776

There is also shlwapi's (Shell API) PathIsDirectory.

Upvotes: 0

detra83
detra83

Reputation: 739

f you are OK with using Windows classes, then simply use this

Directory::Exists(path)

If true, then you have a folder. Similarly use

File::Exists(path)

if you want to determine if a path is a file or not.

Upvotes: 0

Andrew White
Andrew White

Reputation: 53496

I would recommend using is_directory from Boost's Filesystem library...

is_directory( "foo" )

Upvotes: 3

Marc B
Marc B

Reputation: 360682

There's the stat() function family for this, which return metadata about a file/directory, including its type: http://msdn.microsoft.com/en-us/library/14h5k7ff.aspx

Upvotes: 0

Mat
Mat

Reputation: 206699

Use one of the stat variants, and test the st_mode bit.

Upvotes: 1

hmjd
hmjd

Reputation: 121971

GetFileAttributes() would provide this information:

const DWORD result = GetFileAttributes("C:\\path\\x");

if (INVALID_FILE_ATTRIBUTES == result)
{
    std::cerr << "Error: " << GetLastError() << "\n";
}
else if (FILE_ATTRIBUTE_DIRECTORY == (result & FILE_ATTRIBUTE_DIRECTORY))
{
    std::cout << "Is directory\n";
}
else
{
    std::cout << "Is file\n";
}

Upvotes: 5

Related Questions