如何确定文件是否是目录(最佳方式)
我正在使用独立于操作系统的文件管理器,并且在正确检测文件是否是 Windows 上的目录时遇到问题。 Windows 上的 dirent
结构似乎没有 DT_DIR
字段,因此我使用:
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;
但是,这并不总是准确的,因为某些文件被标记为目录(例如,pagefile.sys)。此外,如果您有很多文件,GetFileAttributes
会相当慢。
我还有一个函数:
int does_dir_exist(char *path)
{
DIR *dp_test;
dp_test = opendir(path);
if(dp_test)
{
return 1;
closedir(dp_test);
}
return 0;
}
但这非常慢(对 10000 个文件执行此操作不是一个好主意)。
当然,我可以将两者结合起来,这会非常快,但是有更好的方法吗?
PS 由于某种原因,无法正确格式化第二个函数的代码。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用 GetFileAttributes() 即可。
opendir
和linedir
不会更快(您是否对其进行了分析?您是否重复测试以避免缓存影响?)。是的,
GetFileAttributes()
是准确的。您认为它失败的原因是,当您尝试获取pagefile.sys
的属性时,它失败并返回INVALID_FILE_ATTRIBUTES
,即(DWORD)-1
。当您使用FILE_ATTRIBUTE_DIRECTORY
进行测试时,它会返回 true,因为-1
已设置其中的所有位。你在多少个文件上运行这个?无论您使用什么函数,这都将是 I/O 密集型操作,因为为了确定文件的属性,必须从磁盘(或磁盘缓存)读取父目录。
Just use
GetFileAttributes()
.opendir
andclosedir
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 ofpagefile.sys
, it's failing and returningINVALID_FILE_ATTRIBUTES
, which is(DWORD)-1
. When you test that with theFILE_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).
如果您使用这些方法来确定文件夹中的元素,您将免费获得 GetFileAttributes 结果。
If you use those methods to determine the elements in a folder you get the GetFileAttributes result for free.