Okay, so I'm trying to create a list of he folders, and sub-folders and their files, but right now it doesn't print anything, and seems to be going into an infinite loop. Any idea why?
//infinate loop start
for(int j = 0; j < (int) dirs[i].folders.size(); j++){
dirs.push_back(Directory(dirs[i].folders[j]));
getfiles(dirs[i].dir,dirs[i].files);
getfolders(dirs[i].dir,dirs[i].folders);
}
//infinate loop end
Here is the full source:
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
struct Directory{
public:
int indent;
vector<string> files;
vector<string> folders;
string dir;
Directory(string mydir){ dir = mydir;}
};
int getfolders (string dir, vector<string> &folders)
{
DIR *dp;
struct stat st;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
stat(dirp->d_name, &st);
if(S_ISDIR(st.st_mode)){
if(dirp->d_name[0] != '.')
folders.push_back(string(dirp->d_name));
}
}
closedir(dp);
return 0;
}
/*function... might want it in some class?*/
int getfiles (string dir, vector<string> &files)
{
DIR *dp;
struct stat st;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
stat(dirp->d_name, &st);
if(!S_ISDIR(st.st_mode)){
files.push_back(string(dirp->d_name));
}
}
closedir(dp);
return 0;
}
int main()
{
struct Directory root = Directory(".");
vector<string> display = vector<string>();
cout << "hello\n";
getfiles(root.dir,root.files);
getfolders(root.dir,root.folders);
cout << "hello\n";
vector<Directory> dirs = vector<Directory>();
for(int i = 0; i < (int) root.folders.size(); i++){
dirs.push_back(Directory(root.folders[i]));
getfiles(dirs[i].dir,dirs[i].files);
getfolders(dirs[i].dir,dirs[i].folders);
//infinate loop start
for(int j = 0; j < (int) dirs[i].folders.size(); j++){
dirs.push_back(Directory(dirs[i].folders[j]));
getfiles(dirs[i].dir,dirs[i].files);
getfolders(dirs[i].dir,dirs[i].folders);
}
//infinate loop end
}
cout << "hello\n";
for (int i = 0; i < (int) root.folders.size();i++) {
cout << root.folders[i] << endl;
for(int j = 0; j < (int) dirs[i].folders.size(); j++){
cout << dirs[i].folders[j] << endl;
}
}
return 0;
}