【问题标题】:How do I check if a directory is a file or folder? [duplicate]如何检查目录是文件还是文件夹? [复制]
【发布时间】:2011-04-20 03:53:12
【问题描述】:

好的,所以我正在使用 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;
}

【问题讨论】:

  • 请注意stat() 在成功时返回 0,在失败时返回 -1,零值并不能告诉您它是否是一个目录(-1 告诉您它不是)。跨度>
  • 另外,请查看SO 3828192

标签: c++ file directory dirent.h


【解决方案1】:

boost::filesystem::is_directory()

//I found it )  

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

(^_^)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-31
    • 2015-06-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    相关资源
    最近更新 更多