I am trying to get all the sub-directories of a parent directory. I know this is a lot easier with boost::filesystem or (in c++17) std::fileystem but I'm having problems seting up boost and I don't want to get VS for c++17 (I'm using MinGW).
Here are the critical parts of my code:
#include<dirent.h>
#include<deque>
#include<iostream>
#include<cstring>
struct Folder {
DIR *directory;
char* path;
};
std::deque<Folder> get_folder(char* path) {
std::deque<Folder> folders;
DIR *dir;
struct dirent *entry;
bool first_time = true;
struct Folder first_one = {};
bool occurences_of_first = 0;
bool folder_has_subdirs = false;
char* full_path;
std::string string_for_c_str;
for(int i = -1; i < (int) folders.size(); i++) {
if (i == -1 and folders.size() == 0) {
i++;
}
dir = opendir(path);
std::cout << "Iteration: " << i << std::endl;
while(dir) {
entry = readdir(dir);
string_for_c_str = std::string(path) + std::string("\\") + std::string(entry->d_name);
full_path = (char*) string_for_c_str.c_str();
if (not (is_folder(full_path) or entry->d_name == "." or entry->d_name == "..")) {
continue;
}
std::cout << "Fullpath: " << full_path << std::endl;
std::cout << "Path: " << path << std::endl;
Folder directory = {opendir(full_path), full_path};
folders.push_back(directory);
folder_has_subdirs = true;
}
std::cout << " Check Point 1" << std::endl;
if (first_time == true) {
first_one = folders.front();
}
std::cout << " Check Point 2" << std::endl;
if (first_time == false) {
if (folders.front() == first_one) {
if (occurences_of_first == 1) {
return folders;
}
else {
occurences_of_first = 1;
}
}
}
std::cout << " Check Point 3" << std::endl;
if (folder_has_subdirs == true) {
folders.push_back(folders.front());
}
std::cout << " Check Point 4" << std::endl;
first_time = false;
}
return folders;
}
int main() {
char path[] = "C:\\MinGW";
std::cout << "Results: " << get_folder(path).size() << std::endl;
return 0;
}
And the output:
Iteration: 0
Fullpath: C:\MinGW\.
Path: C:\MinGW
Fullpath: C:\MinGW\..
Path: C:\MinGW
Fullpath: C:\MinGW\bin
Path: C:\MinGW
Fullpath: C:\MinGW\include
Path: C:\MinGW
Fullpath: C:\MinGW\lib
Path: C:\MinGW
Fullpath: C:\MinGW\libexec
Path: C:\MinGW
Fullpath: C:\MinGW\mingw32
Path: C:\MinGW
Fullpath: C:\MinGW\msys
Path: C:\MinGW
Fullpath: C:\MinGW\share
Path: C:\MinGW
Fullpath: C:\MinGW\var
Path: C:\MinGW
As you can see, the program crashes with no errors before the first "Check Point" but it reaches the end of the while loop. What is going wrong with this program and how do I fix it.
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire