2010-10-02 103 views
1

好的,所以我使用了mingW,直接結構沒有名爲d_type或stat,d_stat或dd_stat的變量。我需要知道如何使用我的直接結構來確定我所擁有的是文件還是文件夾。這是我的代碼。如何檢查目錄是文件還是文件夾?

#include <sys/types.h> 
#include <sys/stat.h> 
#include <dirent.h> 
#include <errno.h> 
#include <vector> 
#include <string> 
#include <iostream> 

using namespace std; 

/*function... might want it in some class?*/ 
int getdir (string dir, vector<string> &files) 
{ 
    DIR *dp; 
    struct stat _buf; 
    struct dirent *dirp; 
    if((dp = opendir(dir.c_str())) == NULL) { 
     cout << "Error(" << errno << ") opening " << dir << endl; 
     return errno; 
    } 

    while ((dirp = readdir(dp)) != NULL) { 

     if(stat(dirp->d_name, &_buf) != 0x4) 
     files.push_back(string(dirp->d_name)); 
    } 
    closedir(dp); 
    return 0; 
} 

int main() 
{ 
    string dir = string("."); 
    vector<string> files = vector<string>(); 

    getdir(dir,files); 

    for (unsigned int i = 0;i < files.size();i++) { 
     cout << files[i] << endl; 
    } 
    return 0; 
} 
+0

注意,'STAT()'成功返回0和-1失敗,零值不告訴你它是否是一個目錄( -1告訴你它不是)。 – 2010-10-02 06:45:17

+0

另外,請查看[SO 3828192](http://stackoverflow.com/questions/3828192/checking-if-a-directory-exist-in-unix-system-call)。 – 2010-10-02 06:48:09

回答

5

boost::filesystem::is_directory() 

//I found it) 

//So, also you can try to call stat() function. (on Windows) 

(^_^)

相關問題