1

Если запускать с правами супер пользователя, то программа работает. С правами обычного пользователя вылетает ошибка сегментирования.

  #include <iostream>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <vector>
#include <algorithm>

using namespace std;

struct stlist {
    char *name;
    int dirCount;
    bool operator<(const stlist &rhs) const { return dirCount > rhs.dirCount; }
};

int main() {
    int f = 0, d=0;
    char cwd[1024];
    DIR* dis;
    DIR* inceptionDir;
    struct dirent * dirName;
    //struct dirent * inDirName;
    struct stat fileStat;
    vector <stlist> fileList, dirList;
    fileList.reserve(256);
    dirList.reserve(256);
    getcwd(cwd, sizeof(cwd));
    strcat(cwd, "/");
    dis=opendir(cwd);
    if(dis){
        while(dirName=readdir(dis)){
            stat(dirName->d_name, &fileStat);
            if(fileStat.st_mode&S_IFREG) {
                fileList.push_back(stlist());
                fileList[f].name = dirName->d_name;
                fileList[f].dirCount = fileStat.st_size;
                f++;
            }
            else if(fileStat.st_mode&S_IFDIR){
                inceptionDir=opendir(dirName->d_name);
                dirList.push_back(stlist());
                dirList[d].name=dirName->d_name;
                while(readdir(inceptionDir)){
                    dirList[d].dirCount++;
                }
                d++;
            }
        }
        closedir(dis);
    }
    else cout<< "Error:" << endl;
    //sort(dirList.begin(), dirList.end(), [] (stlist const& a, stlist const& b){return a.dirCount > b.dirCount;});
    sort(dirList.begin(), dirList.end());
    for(auto i : dirList) cout << i.name <<" "<< i.dirCount <<endl;
    return 0;
}

1 ответ 1

4
inceptionDir=opendir(dirName->d_name);

Нет проверки на открытие каталога. Может быть NULL и тогда во тут может быть ситуация описываемая:

while(readdir(inceptionDir))
1
  • только что понял. Спасибо. Вообще глупая ошибка.
    – AndrewKN
    6 мар 2016 в 9:25

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.