区分C++中的文件夹和文件

Moh*_*rki 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;
Run Code Online (Sandbox Code Playgroud)

}

jwe*_*ich 7

一种方法是:

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

您可以struct direntGNU C Library Manual上查看文档.