2008-09-28 197 views

回答

26

調用GetFileAttributes,並檢查FILE_ATTRIBUTE_DIRECTORY屬性。

+3

如果您需要支持Windows 98,那麼您不能使用此功能。如果您需要Win98支持,請參閱下面有關PathIsDirectory的回答。 – jeffm 2008-09-28 23:29:36

85

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 
} 
+2

我用這段代碼遇到的唯一問題是其他情況下的註釋。只是因爲某些不是目錄並不意味着它是一個文件。 – dicroce 2008-09-28 23:27:05

+0

@dicroce:是的,真的夠了;固定。 – 2008-09-29 00:54:55

+0

當我嘗試使用這個,我得到「聚合」主要(int,char **)::統計s'具有不完整的類型,無法定義「,真的無法得到什麼是錯誤。它首先在struct stat的行中給出錯誤;可能是我的錯誤? – MeM 2015-03-30 13:40:26

13

在Win32中,我通常使用PathIsDirectory及其姐妹函數。這適用於Windows 98中,其中GetFileAttributes不(根據MSDN文檔)。

-1

更容易嘗試FileInfo.isDir()在QT

-1

如果您使用CFile你可以嘗試

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

使用C++ 14/C++ 17,您可以使用來自filesystem library的與平臺無關的is_directory()is_regular_file()

#include <filesystem> // C++17 (or Microsoft-specific implementation in C++14) 

std::string pathString = "/my/path"; 
std::filesystem::path path(pathString); // Construct the path from a string. 
if (path.is_directory()) { // Using the non-throwing overload. 
    // Process a directory. 
} 
if (path.is_regular_file()) { // Using the non-throwing overload. 
    // Process a regular file. 
} 

在C++ 14中使用std::experimental::filesystem

#include <experimental/filesystem> // C++14 

std::experimental::filesystem::path path(pathString); 

在部分File types更多的檢查可用。

相關問題