您能否告诉我,如何在以下代码中将文件名(不包含目录)放入我的 vector 中?

int getDir (string dir, vector<string> &files)
{
    DIR *dp;
    struct dirent *dirp;

    if ((dp = opendir(dir.c_str())) == NULL) {
        cout << "Error (" << errno << ") with " << dir << endl;
        return errno;
    }

    while ((dirp = readdir(dp)) != NULL) {
        cout << dirp << endl;
        files.push_back(string(dirp->d_name));
    }

    closedir(dp);
    return 0;
}

最佳答案

试试这个:

struct stat eStat;
stat(dirp->d_name, &eStat);
if(S_ISDIR(eStat.st_mode))
    printf("found directory %s\n", dirp->d_name);

最好用S_ISREG代替S_ISDIR

关于c++ - 用Dirent提取文件名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6059731/

10-11 22:53