如何确定给定的路径是目录还是文件? (C / C ++)
时间:2020-03-06 14:51:16 来源:igfitidea点击:
我正在使用C,有时我必须处理类似
- C:\无论
- C:\任何\
- C:\ What \ Somefile
有没有办法检查给定路径是目录还是给定路径是文件?
解决方案
在Windows上,可以在打开的句柄上使用GetFileAttributes。
调用GetFileAttributes,并检查FILE_ATTRIBUTE_DIRECTORY属性。
stat()会告诉我们这一点。
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 }
在Win32中,我通常使用PathIsDirectory及其姐妹函数。这在Windows 98中起作用,而GetFileAttributes则不起作用(根据MSDN文档。)