-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdirectory-tree-print.cpp
106 lines (90 loc) · 2.72 KB
/
directory-tree-print.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
using std::cout;
using std::string;
using std::vector;
using std::endl;
using std::ifstream;
void printDirectoryStructure(string dir, string prefix, vector<string>& ignore) {
string filepath;
DIR *dp;
struct dirent *dirp;
struct stat filestat;
/**
* Open current directory
*/
dp = opendir(dir.c_str());
/**
* Error check & base case
*/
if (dp == NULL) {
cout << "Error " << errno << " while trying opening" << dir << endl;
return;
}
/**
* Read all files and folders in current directory
*/
while (dirp = readdir(dp)) {
/* Setup file path string, i.e. "Git/cpp/folder1/file.txt" */
filepath = dir + "/" + dirp->d_name;
/* Will only get the file.txt in the above string */
string nameString(dirp->d_name);
/* If either the filepath or the nameString exist in the ignore vector, do not print them */
if(std::find(ignore.begin(), ignore.end(), nameString) != ignore.end() || std::find(ignore.begin(), ignore.end(), filepath) != ignore.end()) {
continue;
} else {
string tmpprefix = prefix;
tmpprefix.replace(tmpprefix.size()-3, 3, "├─");
cout << tmpprefix << dirp->d_name << endl;
}
/**
* Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error.
* http://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html
*/
if (stat(filepath.c_str(), &filestat)) {
continue;
}
/**
* If we're viewing a directory, recurse through its contents (DFS)
*/
if (S_ISDIR(filestat.st_mode)) {
printDirectoryStructure(filepath, prefix + " │", ignore);
}
}
closedir(dp);
}
vector<string> buildIgnoreVector() {
vector<string> ignore;
/* Ignore the following file and folder names */
ignore.push_back(".");
ignore.push_back("..");
ignore.push_back("node_modules");
ignore.push_back("bower_components");
ignore.push_back(".git");
return ignore;
}
int main(int argc, char *argv[]) {
if (!argv[1]) {
cout << "You must type a directory name" << endl;
return -1;
}
string dir(argv[1]);
vector<string> ignore = buildIgnoreVector();
/**
* As command line arguments, pass any file or directory name you wish to ignore after the directory you wish to view
*/
for (int i = 2; i < argc; ++i) {
ignore.push_back(string(argv[i]));
}
cout << "." << endl;
printDirectoryStructure(dir, "│", ignore);
cout << endl << "Dom Farolino\ndomfarolino.com\n<[email protected]>\n<[email protected]>\n";
return 0;
}