Radu
Radu

Reputation: 973

How to find out if a file is a directory (optimal way)

I am working at an OS independent file manager, and I am having a problem with properly detecting if a file is a directory or not on Windows. The dirent structure on windows doesn't appear to have a DT_DIR field, so I am using:

file_attributes=GetFileAttributes(ep->d_name);
if(file_attributes & FILE_ATTRIBUTE_DIRECTORY)files_list[i].is_dir=1;
else files_list[i].is_dir=0;

However, this is not always accurate, as some files are marked as directories (for example, pagefile.sys). Besides, GetFileAttributes is rather slow if you have a lot of files.

I also have a function:

int does_dir_exist(char *path)
{
DIR *dp_test;

dp_test = opendir(path);
if(dp_test)
    {
        return 1;
        closedir(dp_test);
    }

return 0;
  }

But this is pretty slow (won't be a good idea to do it on 10000 files).

Of course, I can combine both which would be pretty fast, but is there a better way?

P.S. For some reason can't format the code properly for the second function.

Upvotes: 1

Views: 1321

Answers (2)

Adam Rosenfield
Adam Rosenfield

Reputation: 400146

Just use GetFileAttributes(). opendir and closedir are not going to faster (did you profile it? Did you repeat your tests to avoid cache effects?).

Yes, GetFileAttributes() is accurate. The reason you think it's failing is because when you try to get the attributes of pagefile.sys, it's failing and returning INVALID_FILE_ATTRIBUTES, which is (DWORD)-1. When you test that with the FILE_ATTRIBUTE_DIRECTORY, it returns true, because -1 has every bit set in it.

How many files are you running this on? Whatever function you use, this is going to be an I/O-bound operation, since in order to determine a file's attributes, the parent directory has to be read from disk (or the disk cache).

Upvotes: 5

Totonga
Totonga

Reputation: 4366

_wfinddata_t fd;
_wfindfirst
_wfindnext
_findclose

If you use those methods to determine the elements in a folder you get the GetFileAttributes result for free.

Upvotes: 1

Related Questions