2012-02-15 14 views
6

このコードでは、ディレクトリを開き、リストが通常のファイルではない(フォルダであることを意味する)かどうかをチェックします。 C++でファイルとフォルダを区別するにはどうしたらいいですか?この場合に役立ちます はここに私のコードです: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

使用 'stat'(または' lstat')とは異なる場合は、元のディレクトリとファイル名にパッチを適用する必要があると思いますし、 'S_ISDIR'。 –

答えて

7

一つの方法は、次のようになります。

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

あなたはGNU C Library Manualstruct direntマニュアルを参照してくださいすることができます。

1

完全にするために、別の方法は次のようになります。

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; 

それは.

関連する問題