2012-02-15 19 views
6

Ho questo codice che apre una directory e controlla se l'elenco non è un file normale (significa che è una cartella) lo aprirà anche. Come posso distinguere tra file e cartelle con C++. Ecco il mio codice se questo aiuta:Distinguere tra cartelle e file in C++

#include <sys/stat.h> 
#include <cstdlib> 
#include <iostream> 
#include <dirent.h> 
using namespace std; 

int main(int argc, char** argv) { 

// Pointer to a directory 
DIR *pdir = NULL; 
pdir = opendir("."); 

struct dirent *pent = NULL; 

if(pdir == NULL){ 
    cout<<" pdir wasn't initialized properly!"; 
    exit(8); 
} 

while (pent = readdir(pdir)){ // While there is still something to read 
    if(pent == NULL){ 
    cout<<" pdir wasn't initialized properly!"; 
    exit(8); 
} 

    cout<< pent->d_name << endl; 
} 

return 0; 

}

+0

Usa 'stat' (o' lstat') e 'S_ISDIR'. –

risposta

7

Un modo potrebbe essere:

switch (pent->d_type) { 
    case DT_REG: 
     // Regular file 
     break; 
    case DT_DIR: 
     // Directory 
     break; 
    default: 
     // Unhandled by this example 
} 

è possibile vedere la documentazione struct dirent sul GNU C Library Manual.

1

Per completezza, un altro modo potrebbe essere:

struct stat pent_stat; 
    if (stat(pent->d_name, &pent_stat)) { 
     perror(argv[0]); 
     exit(8); 
    } 
    const char *type = "special"; 
    if (pent_stat.st_mode & _S_IFREG) 
     type = "regular"; 
    if (pent_stat.st_mode & _S_IFDIR) 
     type = "a directory"; 
    cout << pent->d_name << " is " << type << endl; 

Avresti per correggere il nome del file con la directory originale, se diversa dalla .

Problemi correlati